fn main() {
let a = String::from("foo");
let f = || &a;
fn_immut(f);
println!("{}", a);
}
fn fn_immut<F>(f: F)
where F: Fn() -> &String
{
println!("calling Fn closure from fn, {}", f());
}
这段代码无法编译,
rustc
告诉我应该添加一个'static
,如下所示:fn fn_immut<F>(f: F)
where F: Fn() -> &'static String
我试图这样做,但仍然无法正常工作。而且
rustc
也告诉我“此函数的返回类型包含借入的值,但没有要借用的值”。我的问题是:在这段代码中,闭包已经在其作用域内捕获了
a
变量的引用,为什么rustc仍然告诉我“从中借用没有任何值(value)”?
最佳答案
来自编译器的关键消息确实是缺少用于返回字符串的闭包的生存期说明符。由于特征Fn() -> &String
定义的签名没有任何函数参数,因此没有任何值可让编译器从中推断出返回引用的生存期。
error[E0106]: missing lifetime specifier
--> src/main.rs:10:16
|
10 | F: Fn() -> &String,
| ^ help: consider giving it a 'static lifetime: `&'static`
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
在此处添加
'static
并不能解决问题,因为实际上返回的字符串不会具有该生存期。需要在fn_immut
中引入一个新的生存期参数,从中可以将其转换为F
的约束。fn fn_immut<'a, F>(f: F)
where
F: Fn() -> &'a String,
您还可以返回字符串切片(
&str
)而不是&String
。完整代码:fn main() {
let a = String::from("foo");
let f = || &*a;
fn_immut(f);
println!("{}", a);
}
fn fn_immut<'a, F>(f: F)
where
F: Fn() -> &'a str,
{
println!("calling Fn closure from fn, {}", f());
}
Playground
关于rust - 闭包不能返回引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60464422/