error[E0382]: borrow of moved value: `s1` --> main.rs:5:16 | 3 | let s1 = String::from("hello"); | -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait 4 | let s2 = s1; | -- value moved here 5 | println!("{s1}, {s2}"); | ^^ value borrowed here after move | help: consider cloning the value if the performance cost is acceptable | 4 | let s2 = s1.clone(); | ++++++++
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference --> main.rs:7:5 | 7 | some_string.push_str(", world"); | ^^^^^^^^^^^ `some_string` is a `&` reference, so it cannot be borrowed as mutable | help: consider changing this to be a mutable reference | 6 | fn change(some_string: &mut String) { | +++
error[E0499]: cannot borrow `s` as mutable more than once at a time --> 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 | println!("{r1}, {r2}"); | -- first borrow later used here
可变引用和不可变引用混用也不行:
fnmain() { letmut s = String::from("hello");
letr1 = &s; // no problem letr2 = &s; // no problem letr3 = &mut s; // BIG PROBLEM
println!("{r1}, {r2}, and {r3}"); }
报错:
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable --> main.rs:6:14 | 4 | let r1 = &s; // no problem | -- immutable borrow occurs here 5 | let r2 = &s; // no problem 6 | let r3 = &mut s; // BIG PROBLEM | ^^^^^^ mutable borrow occurs here 7 | 8 | println!("{r1}, {r2}, and {r3}"); | -- immutable borrow later used here
error[E0106]: missing lifetime specifier --> main.rs:5:16 | 5 | fn dangle() -> &String { | ^ expected named lifetime parameter | = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static` | 5 | fn dangle() -> &'static String { | +++++++ help: instead, you are more likely to want to return an owned value | 5 - fn dangle() -> &String { 5 + fn dangle() -> String { |
s 在 dangle 内部创建,函数结束时被释放,而我们却返回了指向它的引用 —— 这个引用会指向无效的 String。Rust 不让这么写。