【问题标题】:How can you access methods of an iterator while using it in a for loop? [duplicate]在 for 循环中使用迭代器时如何访问它的方法? [复制]
【发布时间】:2019-06-04 22:52:25
【问题描述】:

我已经为图形遍历实现了一个自定义迭代器。迭代器包含我计划在循环体内访问的状态变量:

#[derive(Clone, Debug)]
pub struct NodeIterator<'a, T: 'a + Data> {
    graph: &'a DAG<T>,

    /// true if we should fetch the nodes recursively (default = true)
    pub recursive: bool,

    /// true if we explore depth first, and after that go for neighour nodes (default=false)
    pub depth_first: bool,

    /// maximum depth to iterate on lower levels
    /// recursive = true : we use recursion to iterate down the hierarchy
    /// recursive =false : we only iterate either through children or parents
    ///                                  (depending on follow_direction field)
    pub max_depth: NodeID,

    /// follow_direction = true : we iterate using 'parents' vec
    /// follow_direction =false : we iterate using 'children' vec
    pub follow_direction: bool,

    /// current node, that was already provided by the iterator
    pub cur_node_id: Option<NodeID>,

    /// index to the current children or parent (while iterating corresponding collection)
    pub cur_index: Option<NodeID>,

    /// current Edge being iterated
    pub cur_edge: Option<Edge>,

    /// current depth (starts from 0)
    cur_depth: u32,
}

impl<'a, T> NodeIterator<'a, T>
where
    T: 'a + Data,
{
    pub fn get_cur_depth(&self) -> u32 {
        self.cur_depth
    }
}

当我在for 循环中使用它时,它会获得对象的所有权:

let it = graph.iter();
for node_entry in it {
    println!(
        "node_id: {}, depth: {},",
        node_entry.node_id,
        it.get_cur_depth()
    );
}

如果我尝试在代码块中使用它,我会收到以下错误:

     ^^ value used here after move

当我尝试访问it.get_cur_depth() 函数时发生错误。您将如何解决此错误以通过方法访问迭代器的内部状态?

【问题讨论】:

标签: rust


【解决方案1】:

当我在for 循环中使用它时,它会获得对象的所有权:

那么不要使用for循环:

fn main() {
    let s = "a b c";
    let mut it = s.chars();

    while let Some(_) = it.next() {
        println!("remaining: {},", it.as_str());
    }
}

另见:

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-08
  • 1970-01-01
  • 1970-01-01
  • 2010-11-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
相关资源
最近更新 更多