小编Pav*_*old的帖子

为什么派生的clone()方法返回引用?

派生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()
}
Run Code Online (Sandbox Code Playgroud)

这将导致错误:

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>`
Run Code Online (Sandbox Code Playgroud)

为什么派生行为如此?

手动实施后,允许避免这种障碍,但令人不快.

impl<'a, T: 'a> Clone for …
Run Code Online (Sandbox Code Playgroud)

rust

6
推荐指数
1
解决办法
1081
查看次数

标签 统计

rust ×1