为什么“需要明确的生命周期限制"?对于 Box<T>指导? [英] Why "explicit lifetime bound required" for Box<T> in struct?
问题描述
编者注:此代码在 RFC 599 已实施,但答案中讨论的概念仍然有效.
Editor's note: This code no longer produces the same error after RFC 599 was implemented, but the concepts discussed in the answers are still valid.
我正在尝试编译此代码:
I'm trying to compile this code:
trait A {
fn f(&self);
}
struct S {
a: Box<A>,
}
我收到此错误:
a.rs:6:13: 6:14 error: explicit lifetime bound required
a.rs:6 a: Box<A>,
我希望 S.a
拥有 A
的一个实例,但不知道这个生命周期在这里是多么合适.我需要做什么才能让编译器满意?
I want S.a
to own an instance of A
, and don't see how that lifetime is appropriate here. What do I need to do to make the compiler happy?
我的 Rust 版本:
My Rust version:
rustc --version
rustc 0.12.0-pre-nightly (79a5448f4 2014-09-13 20:36:02 +0000)
推荐答案
这里的问题是也可以为引用实现 trait,所以如果你没有为 Box 指定所需的生命周期,任何东西都可以存储在那里.
The problem here is that a trait can be implemented for references too, so if you don't specify the required lifetime for Box anything could be stored in there.
您可以在此 rfc.
所以一种可能的解决方案是绑定生命周期所以 Send
(我们把 I 放在 S 中):
So one possible solution is to bind the lifetime so Send
(we put I in S):
trait A {
fn f(&self);
}
struct I;
impl A for I {
fn f(&self) {
println!("A for I")
}
}
struct S {
a: Box<A + Send>
}
fn main() {
let s = S {
a: box I
};
s.a.f();
}
另一个是将生命周期设置为 'a
(我们可以将引用 &I 或 I 设置为 S):
The other is setting the lifetime to 'a
(we can put a reference &I or I to S):
trait A {
fn f(&self);
}
struct I;
impl A for I {
fn f(&self) {
println!("A for I")
}
}
impl <'a> A for &'a I {
fn f(&self) {
println!("A for &I")
}
}
struct S<'a> {
a: Box<A + 'a>
}
fn main() {
let s = S {
a: box &I
};
s.a.f();
}
请注意,这是更通用的,我们可以存储引用和拥有的数据(Send
类型,其生命周期为 'static
),但您需要在任何地方使用生命周期参数类型被使用.
Note that this is more general and we can store both references and owned data (Send
kind that has a lifetime of 'static
) but you require a lifetime parameter everywhere the type is used.
这篇关于为什么“需要明确的生命周期限制"?对于 Box<T>指导?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!