我已經(jīng)在Rust中創(chuàng)建了一個(gè)數(shù)據(jù)結(jié)構(gòu),我想為其創(chuàng)建迭代器。不變的迭代器很容易。我目前有這個(gè),并且工作正常:// 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() }}我想創(chuàng)建一個(gè)返回可變引用的迭代器。我已經(jīng)嘗試過(guò)這樣做,但是找不到一種方法來(lái)編譯它: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() }}編譯會(huì)導(dǎo)致以下錯(cuò)誤: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 | | } | |_____^我不確定如何解釋這些錯(cuò)誤以及如何更改代碼以允許MutEdges返回可變引用。
如何使用返回可變引用的迭代器創(chuàng)建自己的數(shù)據(jù)結(jié)構(gòu)?
慕的地8271018
2019-12-04 12:31:28