#[derive(Clone)]具有弱泛型

时间:2018-06-25 18:02:34

标签: rust

以下代码无法在Rust 1.27和每晚(playground)下编译:

use std::rc::{Rc, Weak};

struct Bar;

#[derive(Clone)]
struct Foo<T> {
    w: Weak<T>,
}

fn main() {
    let r = Rc::new(Bar);
    let w = Rc::downgrade(&r);

    let f = Foo { w };
    let _f2 = f.clone();
}

产生的错误消息是:

error[E0599]: no method named `clone` found for type `Foo<Bar>` in the current scope
  --> src/main.rs:15:17
   |
6  | struct Foo<T> {
   | ------------- method `clone` not found for this
...
15 |     let _f2 = f.clone();
   |                 ^^^^^
   |
   = note: the method `clone` exists but the following trait bounds were not satisfied:
           `Foo<Bar> : std::clone::Clone`
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `clone`, perhaps you need to implement it:
           candidate #1: `std::clone::Clone`

这很奇怪,因为Clone类型是从该类型派生的,我假设如果derive没有失败,那么将实现给定的特征。

为什么会出现此错误?

我也尝试了以下代码:

fn main() {
    let r = Rc::new(Bar);
    let w = Rc::downgrade(&r);
    let f = Foo { w };
    let _f2 = Clone::clone(&f);
}

错误消息很奇怪:

error[E0277]: the trait bound `Bar: std::clone::Clone` is not satisfied
  --> src/main.rs:14:15
   |
14 |     let _f2 = Clone::clone(&f);
   |               ^^^^^^^^^^^^ the trait `std::clone::Clone` is not implemented for `Bar`
   |
   = note: required because of the requirements on the impl of `std::clone::Clone` for `Foo<Bar>`
   = note: required by `std::clone::Clone::clone`

是否暗示derive(Clone)的实现存在错误?

将定义更改为此:

#[derive(Clone)]
struct Foo {
    w: Weak<Bar>,
}

我以为我可能会缺少对T的一般约束,但这可能是什么(T: ?Clone毫无意义)?

0 个答案:

没有答案