がborrowed value does not live long enough
になるのはなぜですか?以下の例:to_string()は "借用した値が十分に長生していません"というエラーを発生させます
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()
}
エラー:
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());
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
なぜコンパイラが中間値を作成することが示唆されていますか?このエラーは混乱します。
あなたは 'to_string'によって生成された値を参照しています。 https://play.rust-lang.org/?gist=b41ea549d5b4add70559827b7d41e58a&version=stable&backtrace=0 –
[ローカル文字列をスライス(&str)として返す]の可能な複製(http: //stackoverflow.com/questions/29428227/return-local-string-as-a-slice-str) –
@ker重複しているとは思わない。同様のはい、しかしまだ十分なIMO :) –