是否有更直接,更易读的方法来完成以下任务:
fn main() {
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [7, 8, 9];
let iter = a.iter()
.zip(b.iter())
.zip(c.iter())
.map(|((x, y), z)| (x, y, z));
}
Run Code Online (Sandbox Code Playgroud)
也就是说,如何从n个迭代中构建迭代器,从而产生n元组?
blu*_*uss 33
您可以使用izip!()crate itertools中的宏,它为任意多个迭代器实现这一点:
use itertools::izip;
fn main() {
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [7, 8, 9];
// izip!() accepts iterators and/or values with IntoIterator.
for (x, y, z) in izip!(&a, &b, &c) {
}
}
Run Code Online (Sandbox Code Playgroud)
你必须在Cargo.toml中添加对itertools的依赖,使用最新的版本.例:
[dependencies]
itertools = "0.8"
Run Code Online (Sandbox Code Playgroud)
han*_*olo 11
您还可以使用提供的命令创建宏.zip,例如
$ cat z.rs
macro_rules! zip {
($x: expr) => ($x);
($x: expr, $($y: expr), +) => (
$x.iter().zip(
zip!($($y), +))
)
}
fn main() {
let x = vec![1,2,3];
let y = vec![4,5,6];
let z = vec![7,8,9];
let zipped = zip!(x, y, z);
println!("{:?}", zipped);
for (a, (b, c)) in zipped {
println!("{} {} {}", a, b, c);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
$ rustc z.rs && ./z
Zip { a: Iter([1, 2, 3]), b: Zip { a: Iter([4, 5, 6, 67]), b: IntoIter([7, 8, 9]), index: 0, len: 0 }, index: 0, len: 0 }
1 4 7
2 5 8
3 6 9
Run Code Online (Sandbox Code Playgroud)