-
Notifications
You must be signed in to change notification settings - Fork 13.6k
Closed
Description
static gs : &str = "global str";
fn main() {
let mut s3 = String::from("Hello, world!");
let s4 = try_it(&s3[..]);
println!("{}", s4);
s3.clear();
println!("s4={}", s4);
}
fn try_it(s: &str) -> &str {
println!("{}", s);
return gs;
}
compile error
error[E0502]: cannot borrow `s3` as mutable because it is also borrowed as immutable
40 | let s4 = try_it(&s3[..]);
| -- immutable borrow occurs here
41 | println!("{}", s4);
42 | s3.clear();
| ^^^^^^^^^^ mutable borrow occurs here
43 | println!("s4={}", s4);
| -- immutable borrow later used here *completely wrong, s4 has nothing to do with s3*
@cramertj 's reply
No, This is not a bug. The elided lifetimes in try_it are assuming that the output &str has the same lifetime as the input &str. To fix this, you can change try_it to -> &'static str.
two points
- compiler actually knows whether the returned slice is s3 or not
- adding &'static is ugly and cannot solve the problem, such as if(xxx) gs else s4
Metadata
Metadata
Assignees
Labels
No labels