Rust 语法上一个变量的值是转移给另外一个变量, 可是有些状况下可能会想变量值转移以后, 自身还能继续使用. 可使用 clone
函数函数
let a = String::from("test");
let b = a.clone();
println!("{}", a);
复制代码
clone
这个函数是在标准库的 std::clone::Clone
trait 里, 既然是个 trait, 也就意味着能够本身实现一套操做, 一般状况下用默认的定义就行了.ui
咱们如今了解到每次绑定变量, 都会发生全部权转移, 可是你会发现写有些东西的时候好像行为跟目前的认知有点不同.spa
let a: i32 = 10;
let b = a;
println!("a = {}", a); // a = 10
复制代码
a
没有使用 clone
还能使用, 缘由是 Rust 有部分类型默认实现了 std::marker::Copy
trait. 像 structs
这类没有默认实现的类型, 想要这样就得实现一下 Copy
.code
fn main() {
let p1 = Point { x: 1.0, y: 1.0 };
let p2 = p1;
println!("p1 = {:?}", p1);
}
#[derive(Debug)]
struct Point {
x: f64,
y: f64,
}
impl Copy for Point {}
复制代码
可是其实这样仍是无法用的, 编译后就报错了, 由于 struct Point
没有实现 Clone
trait.string
pub fn main() {
let p1 = Point { x: 1.0, y: 1.0 };
let p2: Point = p1;
println!("p1 = {:?}", p1);
}
#[derive(Debug)]
struct Point {
x: f64,
y: f64,
}
impl Clone for Point {
fn clone(&self) -> Self {
Self { x: self.x, y: self.y }
}
}
impl Copy for Point {}
复制代码
如今终于好使了. 可是咱们发觉作这些操做很是烦, 咱们注意到 #[derive(Debug)]
这个东西, 恰好 Rust 提供了Clone
, Copy
的属性.it
pub fn main() {
let p1 = Point { x: 1.0, y: 1.0 };
let p2: Point = p1;
println!("p1 = {:?}", p1);
}
#[derive(Debug, Clone, Copy)]
struct Point {
x: f64,
y: f64,
}
复制代码
Rust 默认绑定变量是进行 move
行为, 想要保留 move
前的变量, 可使用 clone
函数, 想要实现基本类型同样的 copy
行为, 咱们能够添加 Clone
, Copy
属性.io