小编Cof*_*lan的帖子

在 Rust 中迭代 Vec 的替代元素的最佳方法是什么?

我有一个Vec<usize>并且想迭代其中的所有偶数元素。基本上我想了解以下 C++ 代码的理想 Rust 等效项:

const std::vector<uint64_t> vector{1, 4, 9, 16, 25};

for (uint64_t index = 0; index < vector.size(); index += 2) {
    std::cout << vector[index] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所得到enumeratefilter

let vector: Vec<usize> = vec![1, 4, 9, 16, 25];

// Prints even-indexed numbers from the Vec.
type PredicateType = fn(&(usize, &usize)) -> bool;
let predicate: PredicateType = |&tuple| tuple.0 % 2 == 0;
for tuple in vector.iter().enumerate().filter(predicate) {
    println!("{:?}", tuple.1); // Prints 1, …
Run Code Online (Sandbox Code Playgroud)

rust

5
推荐指数
1
解决办法
4298
查看次数

标签 统计

rust ×1