1

s単純な構造体のベクトルを反復処理し、構造体に応じて異なる文字列を追加して、文字列を作成したいと考えていますacc

#[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()に a が返された場合&str、コンパイラは文句を言わなかったでしょう。それでは、違いは何ですか?

構築している限り文字列参照を存続させたいことをコンパイラに理解させるにはどうすればよいsですか?

4

2 に答える 2