$ cargo run Compiling ownership v0.1.0 (file:///projects/ownership) error[E0382]: borrow of moved value: `s1` --> src/main.rs:5:28 | 2 | let s1 = String::from("hello"); | -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait 3 | let s2 = s1; | -- value moved here 4 | 5 | println!("{}, world!", s1); | ^^ value borrowed here after move
For more information about this error, try `rustc --explain E0382`. error: could not compile `ownership` due to previous error
fnmain() { lets = String::from("hello"); // s comes into scope
takes_ownership(s); } fntakes_ownership(some_string: String) { // some_string comes into scope println!("{}", some_string); } // Here, some_string goes out of scope and `drop` is called. The backing // memory is freed.
$ cargo run Compiling ownership v0.1.0 (file:///projects/ownership) error[E0499]: cannot borrow `s` as mutable more than once at a time --> src/main.rs:5:14 | 4 | let r1 = &mut s; | ------ first mutable borrow occurs here 5 | let r2 = &mut s; | ^^^^^^ second mutable borrow occurs here 6 | 7 | println!("{}, {}", r1, r2); | -- first borrow later used here
fnmain() { letmut s = String::from("hello world");
letword = &s[..5];
s.push_str("!!"); // error!
println!("the first word is: {}", word);
}
這段代碼會導(dǎo)致編譯錯誤:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
$ cargo run Compiling ownership v0.1.0 (file:///projects/ownership) error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable --> src/main.rs:10:5 | 8 | let word = &s[..5]; | - immutable borrow occurs here 9 | 10 | s.push_str("!!"); // error! | ^^^^^^^^^^^^^^^^ mutable borrow occurs here 11 | 12 | println!("the first word is: {}", word); | ---- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
// `first_word` works on slices of `String`s, whether partial or whole letword = first_word(&my_string[0..6]); letword = first_word(&my_string[..]); // `first_word` also works on references to `String`s, which are equivalent // to whole slices of `String`s letword = first_word(&my_string);
letmy_string_literal = "hello world";
// `first_word` works on slices of string literals, whether partial or whole letword = first_word(&my_string_literal[0..6]); letword = first_word(&my_string_literal[..]);
// Because string literals *are* string slices already, // this works too, without the slice syntax! letword = first_word(my_string_literal); }