【发布时间】: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,它就不会编译。谁能解释一下原因?
【问题讨论】:
-
我相信Is there any way to return a reference to a variable created in a function? 和/或How do I write an iterator that returns references to itself? 的答案已经回答了您的问题。如果您不同意,请edit您的问题来解释差异。否则,我们可以将此问题标记为已回答。
-
TL;DR — 如果您使用
self并使用impl<T> Vector for VectorImplementation1<T>,那么向量将超出范围,并且引用永远不会有效。如果您使用&self并使用impl<T> Vector for VectorImplementation1<T>,那么您将尝试将返回值的引用与您无法命名的生命周期联系起来。