Rust [updated]:该类型的`Copy`特性可能未实现

问题描述 投票:0回答:1

我想在Rust中制作一个通用的字典,以便更快地制作原型,其中的键是String,值是包装在AnyType容器中的类型。

已更新:可在the Rust Playground上找到最小的可复制示例。请注意,仅在结构之上添加普通的derive语句并不能真正满足要求,这就是为什么它不包含在原始内容中的原因。 (此外,请勿编辑此帖子或将其标记为在其他地方已经回答的问题。)

显式错误输出:

   Compiling pydict v0.1.0 (/home/david/rust/pydict)
error[E0204]: the trait `Copy` may not be implemented for this type
  --> src/lib.rs:18:10
   |
8  |     ___value: Rc<RefCell<Box<AT>>>
   |     ------------------------------ this field does not implement `Copy`
...
18 | impl<AT> Copy for AnyType<AT> {}
   |          ^^^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0204`.
error: could not compile `pydict`.

To learn more, run the command again with --verbose.

我的实现看起来像这样:

use std::collections::HashMap;
use std::boxed::Box;
use std::rc::Rc;
use std::cell::RefCell;
use std::clone::Clone;

struct AnyType<AT> {
    ___value: Rc<RefCell<Box<AT>>>
}
impl<AT> AnyType<AT> {
    pub fn new(value: AT) -> AnyType<AT> {
        AnyType { 
            ___value: Rc::new(RefCell::from(Box::new(value)))
        }
    }
}

impl<AT> Copy for AnyType<AT> {}
impl<AT> Clone for AnyType<AT> {
    fn clone(&self) -> Self {
        *self
    }
}

struct Dict<AT> {
    ___self: HashMap<String, AnyType<AT>>
}

impl<AT> Dict<AT> {
    pub fn new(keys: Option<Vec<String>>, values: Option<Vec<AnyType<AT>>>) 
        -> Result<Dict<AT>, &'static str>
    {
        // ...

关于如何解决编译器错误的任何想法?它说:

error[E0204]: the trait `Copy` may not be implemented for this type

我想在Rust中制作一个通用的字典,以便更快地进行原型制作,其中的键是字符串,值是包装在AnyType容器中的类型。更新:最小可复制...

generics rust hashmap generic-programming
1个回答
0
投票

您正在为Copy()实现AnyType,但没有为AT实现。因此,编译器知道不能在所有实例中复制完整类型的AnyType。这是因为您没有指定AT也必须实现Copy。您必须指定一个特征绑定AT: Copy,以告诉Rust也可以复制AT。

© www.soinside.com 2019 - 2024. All rights reserved.