Rust所有权规则:
1. Rust中每一个变量都是自己值的所有者;
2. 每一个值在任一时刻只有一个所有者;
3. 所有者(变量)离开所属作用域后,这个值被丢弃;
fn main() { let s1 = String::from("Hello!"); let s2 = s1; println!("s2 passed: {}", s2); println!("s1 failed: {}", s1); // value borrowed here after move }
Rust中的借用(不让所有权发生转移 "&")
fn echo(s: &String) { println!("echo: {}", s); } fn main() { let s = String::from("A"); echo(&s); // 可以正常输出 println!("main output: {}", s); }
Rust中的可变引用
fn change(s: &mut String) { s.push_str(" changed!"); } fn main() { let mut s = String::from("variable-s"); change(&mut s); println!("after change: {}", s); }
同一时刻至多只能有一个可变引用
fn main() { let mut s = String::from("var s"); let s_ref1 = &mut s; let s_ref2 = &mut s; println!("{}", s_ref1); println!("{}", s_ref2); // error: second mutable borrow occurs here }
标签:mut,String,--,let,fn,println,随笔,Rust From: https://www.cnblogs.com/fanqshun/p/17011467.html