在搜索有关conservative impl trait 的文档时,I found this example :
struct A {
x: [(u32, u32); 10]
}
impl A {
fn iter_values<'a>(&'a self) -> impl 'a + Iterator<Item = u32> {
self.x.iter().map(|a| a.0)
}
}
生命周期 'a
在返回类型中意味着什么?
我知道 this question about lifetime bound in Box
,但我认为用例是不同的。如果我很好理解答案:
trait object is only valid for the lifetime 'a
这意味着堆中某处的特征对象将在整个生命周期内持续'a
。
但在这里,这不是特征对象,而是存在于堆栈中的具体对象。因此编译器不需要提示其生命周期。
我错过了什么?
最佳答案
语法 impl Iterator<Item = u32> + 'a
意味着
- 将返回函数定义的某些类型,但您不知道确切的类型。那是
impl ...
部分。 - 未指定的具体类型将是
u32
的迭代器值。那是Iterator<Item = u32>
部分。 - 未指定的具体类型可能包含引用,生命周期为
'a
.那是+ 'a
部分。
在您的示例中,返回的迭代器包含对 self
的引用, 所以它不能比 A
的实例活得更长,否则无效。具体类型(如果我们可以写的话)将是 iter::Map<slice::Iter<'a, (u32, u32)>, <closure>>
— 注意它有一个 'a
It means that the trait object that lives somewhere in the heap will last during a lifetime
'a
.
这并不完全正确。这两种情况具有相同的含义:未指定的具体类型可能包含引用。对于特征对象,具体类型位于某种指针后面( Box
、 &
、 Rc
等)。使用 impl trait,具体类型直接放在堆栈上。
this is not a trait object but a concrete object that lives in the stack
Trait 对象不需要堆;他们只能利用堆栈:
let x: &std::fmt::Display = &42;
println!("{}", x);
另见:
关于generics - 返回保守的 impl 特征时,生命周期意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50351879/