我正在尝试创建一个 ScopeRunner 类型,它可以存储对实现 Scope 特性的类型方法的方法调用,如下所示:
trait Scope {
fn run(&self) -> String;
}
struct ScopeImpl;
impl Scope for ScopeImpl {
fn run(&self) -> String {
"Some string".to_string()
}
}
struct ScopeRunner {
runner: Box<dyn Fn() -> String>,
}
impl ScopeRunner {
fn new<S: Scope>(scope: S) -> Self {
ScopeRunner {
runner: Box::new(move || scope.run())
}
}
pub fn run(self) -> String {
(self.runner)()
}
}
fn main() {
let scope = ScopeImpl {};
let scope_runner = ScopeRunner::new(scope);
dbg!(scope_runner.run());
}
我希望因为 ScopeRunner::new
创建了一个移动闭包,这会导致作用域被移动到闭包中。但是借用检查器却给了我这个错误:
error[E0310]: the parameter type `S` may not live long enough
--> src/main.rs:21:30
|
20 | fn new<S: Scope>(scope: S) -> Self {
| -- help: consider adding an explicit lifetime bound `S: 'static`...
21 | ScopeRunner {runner: Box::new(move || scope.run())}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: ...so that the type `[closure@src/main.rs:21:39: 21:58 scope:S]` will meet its required lifetime bounds
--> src/main.rs:21:30
|
21 | ScopeRunner {runner: Box::new(move || scope.run())}
|
当我将 ScopeRunner::new
替换为仅采用 ScopeImpl
的非通用版本时,此代码确实有效。
fn new(scope: ScopeImpl) -> Self {
ScopeRunner {
runner: Box::new(move || scope.run())
}
}
我不明白为什么这是不同的。在我看来,通用 Scope
的生命周期似乎与具体版本相同。
最佳答案
问题在于 S
可以是具有 Scope
impl 的任何类型,其中包括各种尚未存在的类型,这些类型带有对其他类型的引用。例如你可以有这样的实现:
struct AnotherScope<'a> {
reference: &'str,
}
impl Scope for ScopeImpl {
fn run(&self) -> String {
self.reference.to_string()
}
}
Rust 很谨慎,希望确保这适用于任何 符合条件的 S
,包括它是否包含引用。
最简单的解决方法是按照错误说明的建议去做,只是禁止 S
拥有任何非静态引用:
fn new<S: Scope + 'static>(scope: S) -> Self {
ScopeRunner {
runner: Box::new(move || scope.run())
}
}
使用 'static
有效地限制 S
意味着 S
可以包含对具有 'static
的值的引用生命周期或根本没有引用。
如果你想更灵活一点,你可以将其扩展到比 ScopeRunner
本身更长的引用:
struct ScopeRunner<'s> {
runner: Box<dyn Fn() -> String + 's>,
}
impl<'s> ScopeRunner<'s> {
fn new<S: Scope + 's>(scope: S) -> Self {
ScopeRunner {
runner: Box::new(move || scope.run())
}
}
pub fn run(self) -> String {
(self.runner)()
}
}
关于generics - 为什么移动闭包不会捕获具有通用类型的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56331710/