構造体に応じてacc
に異なる文字列を追加して、単純な構造体のベクトルを反復して文字列s
を作成します。一致内の参照を折りたたむと生涯エラーが発生する
#[derive(Clone, Debug)]
struct Point(Option<i32>, Option<i32>);
impl Point {
fn get_first(&self) -> Option<i32> {
self.0
}
}
fn main() {
let mut vec = vec![Point(None, None); 10];
vec[5] = Point(Some(1), Some(1));
let s: String = vec.iter().fold(
String::new(),
|acc, &ref e| acc + match e.get_first() {
None => "",
Some(ref content) => &content.to_string()
}
);
println!("{}", s);
}
次のエラーで、このコードの結果を実行:
error: borrowed value does not live long enough
Some(ref content) => &content.to_string()
^~~~~~~~~~~~~~~~~~~
note: reference must be valid for the expression at 21:22...
|acc, &ref e| acc + match e.get_first() {
^
note: ...but borrowed value is only valid for the expression at 23:33
Some(ref content) => &content.to_string()
^~~~~~~~~~~~~~~~~~~~
問題は、私が作成&str
の寿命がすぐに終わるように見えるということです。しかし、to_string()
が最初に&str
を返した場合、コンパイラは不平を言うことはありません。それでは、違いは何ですか?
s
を作成している限り、文字列参照を有効にすることをコンパイラに理解させるにはどうすればよいですか?
(FYI:各ブランチへの 'acc +'の移動:https://play.rust-lang.org/?gist=95adc6ff8736d21b941a8a89ef67f582&version=stable&backtrace=0) – Dogbert
はい、あります。私はこの投稿をする前に試していない最後のものでなければならない。どうして? – lsund
accの有効期間がmatch文よりも大きいためです。マッチに組み込まれた新しい文字列は、ブロック内にのみ存在します。 – ljedrz