具有寿命参数的特征意味着什么? [英] What does it mean for a trait to have a lifetime parameter?
问题描述
我了解生命周期参数如何应用于函数和结构,但是特征具有生命周期参数意味着什么?是将生命周期参数引入其方法的捷径,还是其他?
I understand how lifetime parameters apply to functions and structs, but what does it mean for a trait to have a lifetime parameter? Is it a shortcut to introduce a lifetime parameter to its methods, or is it something else?
推荐答案
如果您的特征具有生命周期约束,那么该特征的 implementor 可以参与相同的生命周期.具体来说,这使您可以存储具有该生存期的引用.它不是不是的快捷方式,用于指定成员方法的生存期,而那样的方式则使困难和令人困惑的错误消息成为现实!
If you have a trait with a lifetime bound, then implementors of the trait can participate in the same lifetime. Concretely, this allows you to store references with that lifetime. It is not a shortcut for specifying lifetimes on member methods, and difficulty and confusing error messages lie that way!
trait Keeper<'a> {
fn save(&mut self, v: &'a u8);
fn restore(&self) -> &'a u8;
}
struct SimpleKeeper<'a> {
val: &'a u8,
}
impl<'a> Keeper<'a> for SimpleKeeper<'a> {
fn save(&mut self, v: &'a u8) {
self.val = v
}
fn restore(&self) -> &'a u8 {
self.val
}
}
请注意,如何在生命周期中同时对struct和trait进行参数化,并且该生命周期相同.
Note how both the struct and the trait are parameterized on a lifetime, and that lifetime is the same.
SimpleKeeper<'a>
的save()
和restore()
的非特征版本会是什么样?
What would the non-trait versions of
save()
andrestore()
look like forSimpleKeeper<'a>
?
实际上非常相似.重要的部分是该结构本身存储了引用,因此它需要为内部的值提供一个生命周期参数.
Very similar, actually. The important part is that the struct stores the reference itself, so it needs to have a lifetime parameter for the values inside.
struct SimpleKeeper<'a> {
val: &'a u8,
}
impl<'a> SimpleKeeper<'a> {
fn save(&mut self, v: &'a u8) {
self.val = v
}
fn restore(&self) -> &'a u8 {
self.val
}
}
它们的含义与特征版本完全一样吗?
And would they mean exactly the same thing as the the trait version?
是的!
这篇关于具有寿命参数的特征意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!