Closed
Description
There is a minimal repro at #67222 (comment) by @andreytkachenko
Sorry for the unclear title, but I found it hard to explain the situation I'm in. The following code leads to an E0597 error
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
fn main() {
let mut s: HashMap<String, String> = HashMap::new();
s.insert("a".to_owned(), "aa".to_owned());
s.insert("b".to_owned(), "bb".to_owned());
let mut s = Rc::new(RefCell::new(s));
if let Some(o) = s.borrow().get("a") {
println("{}, o);
}
else {
// DO NOTHING
}
}
Which leads to:
error[E0597]: `s` does not live long enough
--> src/main.rs:10:22
|
10 | if let Some(o) = s.borrow().get("a") {
| ^---------
| |
| borrowed value does not live long enough
| a temporary with access to the borrow is created here ...
...
16 | }
| -
| |
| `s` dropped here while still borrowed
| ... and the borrow might be used here, when that temporary is dropped and runs the destructor for type `std::cell::Ref<'_, std::collections::HashMap<std::string::String, std::string::String>>`
|
However, if I add some more statement before the main function ends, even a totally irrelevant print statement, the error disappear.
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
fn main() {
let mut s: HashMap<String, String> = HashMap::new();
s.insert("a".to_owned(), "aa".to_owned());
s.insert("b".to_owned(), "bb".to_owned());
let mut s = Rc::new(RefCell::new(s));
if let Some(o) = s.borrow().get("a") {
println("{}, o);
}
else {
// DO NOTHING
}
println("hello!"); // <----- This line added!!
}
The platform is as follow:
5.0.0-37-generic #40~18.04.1-Ubuntu SMP Thu Nov 14 12:06:39 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
And the rustc version: rustc 1.41.0-nightly (7dbfb0a8c 2019-12-10)
Thanks!
Metadata
Metadata
Assignees
Labels
No labels