Deriving the Clone
trait for a struct containing a reference to object of generic type (Unless it has Clone
bound. In that case cloning work as expected) will generate clone()
method which returns a reference to object but not a new object.
I have the code:
#[derive(Clone)]
struct A<'a, T: 'a>{
ref_generic: &'a T
}
fn test_call<'a, T: 'a>(a: &A<'a, T>)->A<'a, T>{
a.clone()
}
Which will cause an error:
error[E0308]: mismatched types
--> src/lib.rs:15:5
|
14 | fn test_call<'a, T: 'a>(a: &A<'a, T>)->A<'a, T>{
| -------- expected `A<'a, T>` because of return type
15 | a.clone()
| ^^^^^^^^^ expected struct `A`, found &A<'_, T>
|
= note: expected type `A<'a, T>`
found type `&A<'_, T>`
Why does derive behave this way?
Following manual implementation allow to avoid this obstacle but unpleasant.
impl<'a, T: 'a> Clone for A<'a, T>{
fn clone(&self)->Self{
A{ref_generic: self.ref_generic}
}
}