Why is to_string()
causing borrowed value does not live long enough
error? Example below:
use std::collections::HashMap;
struct Foo {
id: Option<usize>,
name: String
}
fn main() {
let foos = getFoos();
for foo in foos {
let mut map = HashMap::new();
map.insert("name", &foo.name);
map.insert("id", &foo.id.unwrap().to_string());
}
}
fn getFoos() -> Vec<Foo> {
Vec::new()
}
Error:
src/main.rs:15:27: 15:54 error: borrowed value does not live long enough
src/main.rs:15 map.insert("id", &foo.id.unwrap().to_string());
^~~~~~~~~~~~~~~~~~~~~~~~~~~
src/main.rs:13:38: 16:6 note: reference must be valid for the block suffix following statement 0 at 13:37...
src/main.rs:13 let mut map = HashMap::new();
src/main.rs:14 map.insert("name", &foo.name);
src/main.rs:15 map.insert("id", &foo.id.unwrap().to_string());
src/main.rs:16 }
src/main.rs:15:9: 15:56 note: ...but borrowed value is only valid for the statement at 15:8
src/main.rs:15 map.insert("id", &foo.id.unwrap().to_string());
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/main.rs:15:9: 15:56 help: consider using a `let` binding to increase its lifetime
src/main.rs:15 map.insert("id", &foo.id.unwrap().to_string());
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Why is compiler suggesting to create intermediate value? This error is confusing.