The following code in Rust builds and runs:
fn func(s: &mut String) -> i32 {
s.push_str("!");
println!("{}", s);
1
}
fn main() {
let mut x = String::from("hello world");
let v = func(&mut x);
println!("{}", v);
let r = &x[..];
println!("{}", r);
}
If the return type of func is changed to &str, I get
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
--> src/main.rs:11:18
|
9 | let v = func(&mut x);
| - mutable borrow occurs here
10 | println!("{}", v);
11 | let r = &x[..];
| ^ immutable borrow occurs here
12 | println!("{}", r);
13 | }
| - mutable borrow ends here
I know that in a given scope, only one mutable reference is allowed, but how does the return type matter?