递归地探索多维向量

时间:2015-05-22 09:01:05

标签: rust

我正在学习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的方法是什么?

1 个答案:

答案 0 :(得分:3)

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

// 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)
}

可以在Enumsthe match constructclosures上的Rust Book章节中找到进一步的相关阅读。