欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > rust 的Clone

rust 的Clone

2025/3/16 18:01:50 来源:https://blog.csdn.net/yinhezhanshen/article/details/146273662  浏览:    关键词:rust 的Clone

Clone 是 Rust 编程语言中一个核心特质(trait), 定义了类型如何安全、明确地创建其值的深拷贝(deep copy)。

下面用实例来演示Clone的作用,先看一下如下的代码,注意此代码编译不过。

#[derive(Debug)]
struct Item{value: i32,
}fn main() {let a = Item{value:7};let b = a;println!("value a {:?}, value b {:?}", a, b);
}

编译报错:

cargo run

error[E0382]: borrow of moved value: `a`
  --> src/main.rs:10:44
   |
8  |     let a = Item{value:7};
   |         - move occurs because `a` has type `Item`, which does not implement the `Copy` trait
9  |     let b = a;
   |             - value moved here
10 |     println!("value a {:?}, value b {:?}", a, b);
   |                                            ^ value borrowed here after move
   |
note: if `Item` implemented `Clone`, you could clone the value
  --> src/main.rs:3:1
   |
3  | struct Item{
   | ^^^^^^^^^^^ consider implementing `Clone` for this type
...
9  |     let b = a;
   |             - you could clone this value
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0382`.
 

 报错的意思是变量a的所有权已经被移动到b,所以println!无法再使用a。

如果要想Item类的变量赋值后所有权继续有效,就需要Item类实现clone()。

方案一:手动为Item类实现trait Clone

#[derive(Debug)]
struct Item{value: i32,
}impl Clone for Item{fn clone(&self) -> Self{Item { value: self.value, }}
}fn main() {let a = Item{value:7};let b = a.clone();println!("value a {:?}, value b {:?}", a, b);
}

 编译运行:

     Running `target\debug\greeting.exe`
value a Item { value: 7 }, value b Item { value: 7 }

方案二:

使用属性(Attribute)

#[derive(Debug, Clone)]
struct Item{value: i32,
}fn main() {let a = Item{value:7};let b = a.clone();println!("value a {:?}, value b {:?}", a, b);
}

编译运行

Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
     Running `target\debug\greeting.exe`
value a Item { value: 7 }, value b Item { value: 7 }

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词