rust(5)-move与copy,借用所有权

fn main() {
    println!("Hello, world!");
	let x=1;
	let mut y=2;
	println!("{}-{}",x,y);
	let z=x+y;
	println!("{}",z);	
	y=6;
	let mut l=0;
	l=x+y;
	println!("{}",l);	
	let k=z;
	println!("{}",k);
	println!("{}",z);

	y=9;
	println!("{}",y);	
}

下面实现了位置表达式z的所有权复制(copy)转移,每个变量(位置表达式)都有自己的内存位置,对该 位置有所有权。在该变量被赋值给其它变量,赋值给其它位置表达式后,会发生所有权转移

let k=z;
Hello, world!
1-2
3
7
3
3
9

下面实现了位置表达式myStr的所有权移动(move)转移, str2对该 位置有所有权,myStr不再有所有权。

fn main() {
    let myStr="Hello, world!".to_string();
    let str2=myStr;	
	println!("{}",myStr)	;
}

编译提示错误:

 ----- move occurs because `myStr` has type `std::string::String`, which does not implement the `Copy` trait

使用&表示借用所有权,直接获取内存位置

fn main() {
    let myStr="Hello, world!".to_string();
    let str2=&myStr;	
	println!("{}",myStr)	;
	println!("{}",str2)	;	
}
learn1.exe
Hello, world!
Hello, world!

而下面语句

let x=&51;

表示生成一个临时值,临时位置表达式,值为51,然后借用给x

发布了385 篇原创文章 · 获赞 13 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/AI_LX/article/details/104478893