我已经在Rust中创建了一个数据结构,我想为其创建迭代器。不变的迭代器很容易。我目前有这个,并且工作正常:// This is a mock of the "real" EdgeIndexes class as// the one in my real program is somewhat complex, but// of identical typestruct EdgeIndexes;impl Iterator for EdgeIndexes { type Item = usize; fn next(&mut self) -> Option<Self::Item> { Some(0) } fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }}pub struct CGraph<E> { nodes: usize, edges: Vec<E>,}pub struct Edges<'a, E: 'a> { index: EdgeIndexes, graph: &'a CGraph<E>,}impl<'a, E> Iterator for Edges<'a, E> { type Item = &'a E; fn next(&mut self) -> Option<Self::Item> { match self.index.next() { None => None, Some(x) => Some(&self.graph.edges[x]), } } fn size_hint(&self) -> (usize, Option<usize>) { self.index.size_hint() }}我想创建一个返回可变引用的迭代器。我已经尝试过这样做,但是找不到一种方法来编译它:pub struct MutEdges<'a, E: 'a> { index: EdgeIndexes, graph: &'a mut CGraph<E>,}impl<'a, E> Iterator for MutEdges<'a, E> { type Item = &'a mut E; fn next(&mut self) -> Option<&'a mut E> { match self.index.next() { None => None, Some(x) => self.graph.edges.get_mut(x), } } fn size_hint(&self) -> (usize, Option<usize>) { self.index.size_hint() }}编译会导致以下错误:error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements --> src/lib.rs:54:24 |54 | Some(x) => self.graph.edges.get_mut(x), | ^^^^^^^^^^^^^^^^ |note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 51:5... --> src/lib.rs:51:5 |51 | / fn next(&mut self) -> Option<&'a mut E> {52 | | match self.index.next() {53 | | None => None,54 | | Some(x) => self.graph.edges.get_mut(x),55 | | }56 | | } | |_____^我不确定如何解释这些错误以及如何更改代码以允许MutEdges返回可变引用。
1 回答
- 1 回答
- 0 关注
- 466 浏览
添加回答
举报
0/150
提交
取消