Chciałbym zrobić kodu następujące opracowują:Lifetime adnotacji do argumentu zamknięcia
struct Provider {}
impl Provider {
fn get_string<'a>(&'a self) -> &'a str { "this is a string" }
}
fn main() {
let provider = Provider{};
let mut vec: Vec<&str> = Vec::new();
// PROBLEM: how do I say that this reference s here
// needs to live as long as vec?
let fun = |s: &str| {
vec.push(s);
};
fun(provider.get_string());
}
Jest to błąd kompilacji, które otrzymuję:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:9:22
|
9 | let mut vec: Vec<&str> = Vec::new();
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the block at 11:24...
--> src/main.rs:11:25
|
11| let fun = |s: &str| {
| ^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:12:18
|
12| vec.push(s);
| ^
note: but, the lifetime must be valid for the block suffix following statement 2 at 13:6...
--> src/main.rs:13:7
|
13| };
| ^
note: ...so that variable is valid at time of its declaration
--> src/main.rs:11:9
|
11| let fun = |s: &str| {
| ^^^
Uh! To zabawne. Czasami naprawdę chciałbym móc użyć "dostawcy", by powiedzieć "życie tego faceta, tam". –
Nie wiem, jak to działa. Aby obejść ten problem, być może pozwolisz, aby zamknięcie przechwyciło s także ze środowiska, zamiast przekazywać je jako parametr. Podobnie jak [this] (https://play.rust-lang.org/?gist=e7fd2f4ee7c58b9e592a1f060b2d396b&version=stable&backtrace=0) –
@Shepmaster od tego też znalazłem. To jest rozwiązanie, które działa również na prawdziwy problem :) Wciąż jestem zaskoczony, że nie można ręcznie określić typu 's' tutaj. – bennofs