在for循环中使用迭代器时,如何访问它的方法?

时间:2019-06-04 22:52:25

标签: rust

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

#[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()函数时发生错误。您将如何解决此错误以通过方法访问迭代器的内部状态?

1 个答案:

答案 0 :(得分:2)

  

for循环中使用它时,它将获得对象的所有权:

然后不要使用for循环:

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

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

另请参阅: