亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用返回可變引用的迭代器創建自己的數據結構?

如何使用返回可變引用的迭代器創建自己的數據結構?

Git
慕的地8271018 2019-12-04 12:31:28
我已經在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 關注
  • 528 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號