PDF
(Move)1Rust(2) OwnershipContentsOwnership ....................................................................................... 1(Move) ..................................................................................... 1使clone(Reference) ....................................................................................... 4(Borrowing) ...................................................................................... 5Ownership使使dropResource Acquisition Is Initialization (RAII){ let s = String::from("hello"); // s is valid from this point forward // do stuff with s} // drop (Move)droplet s1 = String::from("hello");let s2 = s1; (Move)2drop使 --> test.rs:5:9 |5 | let s1 = s; | ^^ help: consider prefixing with an underscore: `_s1` | = note: `#[warn(unused_variables)]` on by defaulterror[E0382]: borrow of moved value: `s` --> test.rs:6:20 |4 | let s = String::from("hello"); | - move occurs because `s` has type `std::string::String`, (Move)3which does not implement the `Copy` trait5 | let s1 = s; | - value moved here6 | println!("{}", s); | ^ value borrowed here after moveerror: aborting due to previous error使clone使clonelet s = String::from("hello");let s1 = s.clone(); // println!("{}\n{}", s, s1); // slet x = 3.14;let y = x; // xprintln!("x={} y={}", x, y);let x = String::from("hello");let y = x;println!("x={} y={}", x, y); // xinvalidCopyCopyCopy使#[derive(Debug, Copy, Clone)]struct Point { x: i32, y: i32,}fn main() { let p1 = Point { x: 10, y: 10 }; let _p2 = p1; println!("p1:{:?}", p1); // PointCopy} (Reference)4fn output(str: String) { println!("=>{}", str);}fn main() { let x = String::from("hello"); output(x); println!("x={}", x); // x}使fn output(str: String) -> String { println!("=>{}", str); str}fn generate() -> String { String::from("hello world!")}fn main() { let x = generate(); let x = output(x); // x println!("x={}", x); // x}(Reference)fn output(str: &String) { println!("=>{}", str);}fn main() { let x = generate(); output(&x); // x println!("x={}", x); // x}& (Borrowing)5let x = String::from("hello world");let y: &String = &x;println!("x={} y={}", x, y); // y(Borrowing)西西12 | fn output(str: &String) { | ------- help: consider changing this to be a mutable reference: `&mut std::string::String`13 | str.push_str("world!"); | ^^^ `str` is a `&` reference, so the data it refers to cannot be borrowed as mutable使&mutfn output(str: &mut String) { str.push_str("world!"); println!("=>{}", str);}fn main() { let mut x = String::from("hello world"); output(&mut x);}使let mut s = String::from("hello");let r1 = &s; // no problemlet r2 = &s; // no problemprintln!("{} and {}", r1, r2);// r1 and r2 are no longer used after this pointlet r3 = &mut s; // no problem// 使r1r2// println!("{} and {}", r1, r2);println!("{}", r3);

HTML view coming soon.

Download PDF for the full formatted version.