递归探索多维向量

Recursively explore a multidimensional vector

我目前正在学习 Rust。在我学习的过程中,我正在尝试转换一个用动态语言编写的小项目。我遇到了一个问题,我正在努力寻找解决方案。

我希望递归访问 n 维向量的每个元素。

以下是问题的概括代码:

explore(collection) {
    for item in collection {
        if item is Collection {
            explore(item)
        }
        else {
            operate(item)
        }
    }
}

我正在使用rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14)

感觉如果不使用不安全代码(我还没有学会)这是不可能的。

我的问题如下:

  1. 目前这在 Rust 中可行吗?
  2. 如果是这样,那么最像 Rust 的方法是什么?

是的。有几种方法可以做到这一点,但没有更多细节,我只是建议以下相对简单的方法:

// In Rust, prefer to use an enum over dynamic dispatch.
enum Item<T> {
    Collection(Vec<Item<T>>),
    Value(T),
}

// This explore function is generic over both the type being stored (T),
// and the operation to be performed on values.
fn explore<T, F>(collection: &[Item<T>], operate: &mut F)
where F: FnMut(&T) {
    for item in collection {
        match item {
            &Item::Collection(ref items) => explore(items, operate),
            &Item::Value(ref value) => operate(value)
        }
    }
}

fn operate_i32(value: &i32) {
    println!("operate({})", value);
}

fn main() {
    use Item::*;

    let root = vec![
        Value(1),
        Collection(vec![
            Value(2),
            Value(3),
        ]),
        Value(4),
    ];

    explore(&root, &mut operate_i32)
}

可以在 Enums, the match construct and closures 上的 Rust Book 章节中找到更多相关阅读材料。