2016-07-18 41 views
0

我可以創建一個類型爲Option<&str>的綁定嗎?微型非工作例如:我可以使用'Option <&str>`類型創建一個綁定嗎?

fn main() { 
    let a: Option<&str> = { 
     Some(&{"a".to_string() + "b"}) // Let's say the string is not static 
    }; 
} 

這是不行的,我需要補充壽命(或使用Option<String>沒有&)。那麼我怎麼能在這裏宣佈一生?我知道我可以返回一個Option<String>,一切都會好的,但那不是我想要的 - 我想了解一些Rust機制。我可以聲明一個函數的生命週期,但不知道如何在一個簡單的let綁定中做到這一點。

回答

2

絕對:

fn main() { 
    let s = "a".to_string() + "b"; 
    let a: Option<&str> = Some(&s); 
} 

的問題不是在創造一個Option<&str>,那就是您要採取的東西,已經超出範圍的參考。這是(一部分),用於在原始代碼中的錯誤消息:

error: borrowed value does not live long enough 
    |>   Some(&{"a".to_string() + "b"}) 
    |>    ^^^^^^^^^^^^^^^^^^^^^^^ does not live long enough 

進一步的信息參見Return local String as a slice (&str)

1

您需要通過將其綁定到另一個名字超出a的初始化表達式字符串的一生:

fn main() { 
    let x: String = "a".to_string() + "b"; 
    let a: Option<&str> = { 
     Some(&x) 
    }; 
} 
1

你試圖保持一個值的引用不活足夠長的時間,像錯誤說:

3 |>   Some(&{"a".to_string() + "b"}) // Let's say the string is not static 
    |>    ^^^^^^^^^^^^^^^^^^^^^^^ does not live long enough 

你可以有Option<&str>類型的綁定,但引用必須比綁定活得更長。在你的例子中,你創建了一個綁定到結果字符串,而不是參考它:

fn main() { 
    let x: String = "a".to_string() + "b"; 
    let a: Option<&str> = Some(&x); 
} 
相關問題