是否可以遍历元组? [英] Is it possible to iterate over a tuple?

查看:69
本文介绍了是否可以遍历元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用循环遍历一个元组,就像在 Python 中一样.Rust 有可能吗?

let tup1 = (1, '2', 3.0);对于我在 tup1.iter() {println!("{}", i);}

解决方案

元组的每个元素的类型可以不同,所以你不能遍历它们.元组甚至不能保证以与类型定义相同的顺序存储它们的数据,因此即使您自己为它们实现 Iterator,它们也不是有效迭代的好候选.p>

但是,数组完全等价于元组,所有元素的类型相同:

let tup = [1, 2, 3];对于我在 tup.iter() {println!("{}", i);}

另见:

I want to iterate over a tuple using a loop, like in Python. Is it possible in Rust?

let tup1 = (1, '2', 3.0);
for i in tup1.iter() {
    println!("{}", i);
}          

解决方案

The type of each element of a tuple can be different, so you can't iterate over them. Tuples are not even guaranteed to store their data in the same order as the type definition, so they wouldn't be good candidates for efficient iteration, even if you were to implement Iterator for them yourself.

However, an array is exactly equivalent to a tuple, with all elements of the same type:

let tup = [1, 2, 3];
for i in tup.iter() {
    println!("{}", i);
}

See also:

这篇关于是否可以遍历元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆