[英]Lifetime bound on generic parameter not required on impl block
I have a simple Wrapper that holds a reference to a slice of type T
. 我有一个简单的Wrapper,其中包含对类型
T
的切片的引用。 My first attempt looked like this: 我的第一次尝试是这样的:
struct SliceWrapper<'a, T> {
a: &'a [T],
}
Now the compiler rightly complains that T
may not live long enough. 现在,编译器正确地抱怨
T
寿命可能不够长。 So I do what it suggests and add a lifetime bound to T
. 因此,我按照建议的方式进行操作,并为
T
添加了生命周期。 Thereby telling the compiler that all borrowed content within T
outlives 'a
. 从而告诉编译器
T
中所有借用的内容都超过了'a
。
This is how my final attempt looks: 这是我最后一次尝试的样子:
#[derive(Debug)]
struct SliceWrapper<'a, T: 'a> {
a: &'a [T],
}
impl<'a, T> SliceWrapper<'a, T> {
fn new(n: &'a [T]) -> SliceWrapper<'a, T> {
SliceWrapper { a: n }
}
}
fn main() {
let array = [1, 2, 3, 4, 5];
let aw = SliceWrapper::new(&array[..2]);
println!("{:?}", aw);
}
This works. 这可行。 But, if I changed the impl to
但是,如果我将展示次数更改为
impl<'a, T: 'a> SliceWrapper<'a, T> {
fn new(n: &'a [T]) -> SliceWrapper<'a, T> {
SliceWrapper { a: n }
}
}
it also works. 它也可以。 Why don't I have to also specify the lifetime bound on the impl block?
为什么不用在impl块上也指定生存期限制? What is different from my first successful attempt where I omitted it on the impl block?
与我在impl块上省略它的第一次成功尝试有什么不同?
I would suggest that defining 我建议定义
struct SliceWrapper<'a, T: 'a>
would implicitly force the bound T: 'a
wherever you use SliceWrapper
. 会隐式强制绑定
T: 'a
无论您T: 'a
何处使用SliceWrapper
。 So both are equivalent: 因此,两者是等效的:
impl<'a, T> SliceWrapper<'a, T> // T: 'a is "contained" in SliceWrapper definition
impl<'a, T: 'a> SliceWrapper<'a, T> // but it doesn't harm to say it again
This is just a feeling, not a well-proven assertion (I didn't check RFCs or compiler code). 这只是一种感觉,而不是经过充分证明的断言(我没有检查RFC或编译器代码)。 It would be consistent with what happens with type inference: you usually have to supply the type once, and can be implicit in most other places.
这将与类型推断发生的情况一致:您通常必须提供一次类型,并且在大多数其他地方都可以隐式提供。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.