gpt4 book ai didi

rust - 闭包参数的生命周期注解

转载 作者:行者123 更新时间:2023-11-29 07:47:45 24 4
gpt4 key购买 nike

我想编译以下代码:

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());
}

Playground link

这是我得到的编译错误:

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| {
| ^^^

最佳答案

如果删除所有生命周期注解并让编译器推断完成其工作,您的代码就可以正常工作:

struct Provider;

impl Provider {
fn get_string(&self) -> &str { "this is a string" }
}

fn main() {
let provider = Provider;
let mut vec = Vec::new();

let mut fun = |s| {
vec.push(s);
};

fun(provider.get_string());
}

简而言之,无法显式引用局部变量的生命周期,只能引用函数参数。不过,编译器知道该怎么做。

如果你真的需要它,你可以创建一个函数来允许注释生命周期:

fn thing<'a>(provider: &'a Provider) -> Vec<&'a str> {
let mut vec: Vec<&'a str> = Vec::new();

{
let mut fun = |s: &'a str| vec.push(s);

fun(provider.get_string());
} // End mutable borrow of `vec`

vec
}

fn main() {
let provider = Provider;
thing(&provider);
}

why did the original annotations stop things from working?

具体来说就是这一点:

let fun = |s: &str| {
vec.push(s);
};

这在闭包上声明了一个新的生命周期。使用编造的语法(你 can't declare lifetimes on closure arguments ),它相当于:

let fun = <'a> |s: &'a str| {
vec.push(s);
};

这就是编译器出错的原因:

the lifetime cannot outlive the anonymous lifetime #1 defined on [the closure's block]

生成的生命周期与 Provider 的生命周期之间没有联系。将其保留在外允许编译器插入所需但不可命名的生命周期。

关于rust - 闭包参数的生命周期注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41849854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com