由于使用了相关类型,我在Rust 1.14中遇到了一生的错误,由以下两个类似的程序演示,第一个编译没有错误,第二个编译有生命周期错误 .
Program #1 — compiles without error
trait Trait<'a> {
type T;
}
struct Impl;
impl<'a> Trait<'a> for Impl {
type T = std::marker::PhantomData<&'a ()>;
}
struct Alpha<'a, T: Trait<'a>> {
_dummy: std::marker::PhantomData<(&'a (), T)>,
}
fn use_alpha<'a>(_: &'a Alpha<'a, Impl>) {}
fn main() {
for x in Vec::<Alpha<Impl>>::new().into_iter() {
use_alpha(&x); // <-- ok
}
}
Program #2 — has the lifetime error
trait Trait<'a> {
type T;
}
struct Impl;
impl<'a> Trait<'a> for Impl {
type T = std::marker::PhantomData<&'a ()>;
}
struct Alpha<'a, T: Trait<'a>> {
_dummy: std::marker::PhantomData<(&'a (), T::T)>,
}
fn use_alpha<'a>(_: &'a Alpha<'a, Impl>) {}
fn main() {
for x in Vec::<Alpha<Impl>>::new().into_iter() {
use_alpha(&x); // <-- !error!
}
}
这是第二个程序的编译时错误:
error: `x` does not live long enough
--> src/main.rs:20:5
|
19 | use_alpha(&x); // <-- !error!
| - borrow occurs here
20 | }
| ^ `x` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
这是两个程序的差异:
#[derive(Clone)]
struct Alpha<'a, T: Trait<'a>> {
- _dummy: std::marker::PhantomData<(&'a (), T)>,
+ _dummy: std::marker::PhantomData<(&'a (), T::T)>,
}
唯一的区别是,通过将第一个程序更改为使用关联类型而不是 struct
定义中的type参数,会发生生命周期错误 . 我不知道为什么会这样 . 据我所知,相关类型不应该产生任何额外的生命周期限制 - 它只是 'a
,但显然Rust编译器不同意 .
如果我用简单的实例化替换第二个程序的 main
函数中的迭代,那么生命周期错误就会消失 . 那是:
fn main() {
let x = Alpha::<Impl> { _dummy: std::marker::PhantomData };
use_alpha(&x); // <-- ok in both programs
}
我不明白为什么迭代与直接实例化有任何不同 .
1 回答
在
use_alpha
中,您使用相同的生命周期来引用Alpha
及其生命周期参数 . 它的生命周期参数然后成为Impl
的Trait::T
的生命周期 . 该注释提供了关于值被删除的顺序的提示:Impl::T
在Impl
之前被删除,因为它是Impl
定义的一部分,但这意味着Alpha
的某些部分在它仍然存在时已被删除 .您可以通过在
use_alpha
中使用两个生命周期参数来解决此问题:这将允许编译器推断每种类型的不同生存期 .