[英]Why doesn't a trait implementation compile for a struct, but it compiles for a reference to the struct?
為了回答我以前的問題之一( 如何用實現Iterator的通用類型實現通用特征? ),將這段代碼提供給我:
pub trait Vector {
type Item;
type Iter: Iterator<Item = Self::Item>;
// several functions
fn iter(&self) -> Self::Iter;
}
pub struct VectorImplementation1<T> {
numbers: Vec<T>,
}
impl<'a, T> Vector for &'a VectorImplementation1<T> {
type Item = &'a T;
type Iter = std::slice::Iter<'a, T>;
fn iter(&self) -> Self::Iter {
self.numbers.iter()
}
}
fn main() {}
我看到該特征是為引用struct而實現的,如果僅使用struct,則無法編譯。 有人可以解釋為什么嗎?
正如編譯器錯誤所提到的,這里的問題是,如果按如下方式實現,則生存期'a
沒有理由存在:
impl<'a, T> Vector for VectorImplementation1<T> {
/**/
}
error[E0207]: the lifetime parameter `'a` is not constrained by the impl
trait, self type, or predicates
--> src/main.rs:13:6
|
13 | impl<'a, T> Vector for VectorImplementation1<T> {
| ^^ unconstrained lifetime parameter
因為在這種情況下,編譯器僅查看定義,而不查看主體。 下面是一種不同的方法,為簡單起見,可能之前沒有提到過:
pub trait Vector<'a> {
type Item: 'a;
type Iter: Iterator<Item = Self::Item> + 'a;
// several functions
fn iter(&'a self) -> Self::Iter;
}
pub struct VectorImplementation1<T> {
numbers: Vec<T>,
}
impl<'a, T: 'a> Vector<'a> for VectorImplementation1<T> {
type Item = &'a T;
type Iter = std::slice::Iter<'a, T>;
fn iter(&'a self) -> Self::Iter {
self.numbers.iter()
}
}
impl<'a, T: 'a> Vector<'a> for &'a VectorImplementation1<T> {
type Item = &'a T;
type Iter = std::slice::Iter<'a, T>;
fn iter(&'a self) -> Self::Iter {
self.numbers.iter()
}
}
在這種情況下,我們將生存期移至特征,以便該特征可以“使用”生存期,從而驗證我們對特征實現的使用。 但是,正如我前面提到的,這增加了需要了解與該特征相關的生存期的復雜性,從而降低了可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.