Obtaining a sign Clone
for a structure containing a reference to an object of a generic type (if it is not associated with Clone
. In this case, cloning works as expected) generates a method clone()
that returns a reference to the object, but not a new object.
I have a code:
struct A<'a, T: 'a>{
ref_generic: &'a T
}
fn test_call<'a, T: 'a>(a: &A<'a, T>)->A<'a, T>{
a.clone()
}
This will result in 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 is this behavior happening this way?
After manual implementation, this obstacle can be avoided, but unpleasantly.
impl<'a, T: 'a> Clone for A<'a, T>{
fn clone(&self)->Self{
A{ref_generic: self.ref_generic}
}
}
source
share