$ cargo build Compiling hello v0.1.0 (/home/spencer/share/my_code/rust_prj/hello) error[E0596]: cannot borrow `*s` as mutable, as it is behind a `&` reference --> src/main.rs:14:5 | 13 | fn append_string(s: &String) { | ------- help: consider changing this to be a mutable reference: `&mut String` 14 | s.push_str(" world"); | ^ `s` is a `&` reference, so the data it refers to cannot be borrowed as mutable
fnmain() { letmut s = String::from("hello"); let r1 = &mut s; let r2 = &mut s; println!("{}, {}", r1, r2); }
编译结果 :
1 2 3 4 5 6 7 8 9 10 11
Compiling hello v0.1.0 (/home/spencer/share/my_code/rust_prj/hello) 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"); { let r1 = &mut s; } let r2 = &mut s; }
错误3
1 2 3 4 5 6 7
fnmain() { letmut s = String::from("hello"); let r1 = &mut s; s.push_str(" world"); r1.push_str(" hello2"); println!("{}", s); }
编译结果 :
1 2 3 4 5 6 7 8 9
error[E0499]: cannot borrow `s` as mutable more than once at a time --> src/main.rs:4:5 | 3 | let r1 = &mut s; | ------ first mutable borrow occurs here 4 | s.push_str(" world"); | ^ second mutable borrow occurs here 5 | r1.push_str(" hello2"); | -- first borrow later used here