推导Clone
包含对泛型类型对象的引用的结构的特征(除非它有Clone
边界。在这种情况下,克隆工作将按预期生成clone()
方法返回对象的引用,但不返回新对象。
我有代码:
#[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()
}
这会导致错误:
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>`
为什么derive会有这样的行为?
手动实施可以避免这个障碍,但令人不快。
impl<'a, T: 'a> Clone for A<'a, T>{
fn clone(&self)->Self{
A{ref_generic: self.ref_generic}
}
}