The following code fails to compile with Rust 1.27 and nightly (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();
}
The resulting error message is:
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`
This is weird because, the Clone
type is derived for that type, and I assume that if a derive
does not fail, then given trait will be implemented.
Why do I get this error?
I also tried this code:
fn main() {
let r = Rc::new(Bar);
let w = Rc::downgrade(&r);
let f = Foo { w };
let _f2 = Clone::clone(&f);
}
The error message is quite curious:
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`
Is that a hint that there is a bug in the implementation of derive(Clone)
?
Changing the definition to this compiles:
#[derive(Clone)]
struct Foo {
w: Weak<Bar>,
}
I thought that I might be missing a generic constraint on T
, but what could it be (T: ?Clone
makes no sense)?