【问题标题】:Why doesn't a trait implementation compile for a struct, but it compiles for a reference to the struct?为什么不为结构编译特征实现,而是为对结构的引用进行编译?
【发布时间】:2019-04-18 19:29:52
【问题描述】:

要回答我之前的一个问题 (How to implement a generic trait with a generic type implementing 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() {}

我看到 trait 是为 struct 的引用而实现的,如果我只使用 struct,它就不会编译。谁能解释一下原因?

【问题讨论】:

标签: reference rust traits


【解决方案1】:

这里的问题,正如编译器错误所提到的,生命周期'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()
    }
}

在这种情况下,我们将生命周期移动到特征,以便特征可以“使用”生命周期,从而验证我们对特征实现的使用。但正如我之前提到的,这增加了需要了解与此特征相关的生命周期的复杂性,从而降低了可读性。

【讨论】:

    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2014-08-19
    • 1970-01-01
    相关资源
    最近更新 更多