有没有办法将迭代器解包成元组? [英] Is there any way to unpack an iterator into a tuple?
本文介绍了有没有办法将迭代器解包成元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么方法可以完成如下操作:
Is there any way to accomplish something like the following:
let v = vec![1, 2, 3];
let (a, b) = v.iter().take(2);
这样,最后是 a = 1
和 b = 2
吗?
Such that a = 1
and b = 2
at the end?
我知道我可以只使用向量,但我想要命名变量.
I know I could just use a vector but I would like to have named variables.
推荐答案
这可能不是您所要求的,但我想您很少想将任意大的向量转换为元组.如果只想将向量的前几个元素提取到元组中,可以使用切片模式匹配:
This may not be exactly what you asked for, but I suppose you rarely want to convert an arbitrarily large vector to a tuple anyway. If you just want to extract the first few elements of a vector into a tuple, you can do so using slice pattern matching:
fn main() {
let v = vec![1, 2, 3];
let (a, b) = match &v[..] {
&[first, second, ..] => (first, second),
_ => unreachable!(),
};
assert_eq!((a, b), (1, 2));
}
这篇关于有没有办法将迭代器解包成元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文