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

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

最佳答案

When I use it in a for loop, it takes ownership of the object:

然后不要使用 for 循环:

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

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

另见:

关于rust - 在 for 循环中使用迭代器时如何访问它的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56452305/

相关文章:

rust - 使用图像箱时如何获得 u8 RGB 值的向量?

web-applications - 在 rust 中使用扭曲来服务静态文件

rust - 在 Rust 中,如何在向量的向量中合并两个子向量?

class - 来自 Python 的类接口(interface)设计可以在 Rust 中得到反射(reflect)吗?

rust - 让 Enumerate 在 Rust 中作为 ExactSizeIterator 工作

vector - 在 Rust 中拥有多个链表并在它们之间移动数据的正确方法是什么?

xml - sxd-document/sxd-xpath 无法解析 XML

rust - 期望 `T: Read` 或 `T: Write` 的通用函数如何接受参数 `&mut T` ?

rust - 为什么可以从函数返回对文字的可变引用?

rust - 简单的 Rust crate 函数整数/ float 错误