如何制作动态索引以获取元组的值? [英] How do I make a dynamic index to get the value of a tuple?
问题描述
在 Python 中,我了解到可以通过动态索引检索元组值:
In Python, I learned that I can retrieve a tuple value by a dynamic index:
data = (1,2,3,4)
data[0]
for a in range(len(data)):
print(data[a])
输出:
1
2
3
4
如何在 Rust 中做到这一点?
how to do this in Rust?
我尝试过这样的事情:
fn main() {
let data = (12, 3, 4, 5);
for a in 0..100 {
println!("{}", data.a);
}
}
但它不起作用,它只会给我一些错误.
But it's not working, it only gives me some error.
推荐答案
正如其他人指出的那样,您可能想要使用数组或 Vec
代替.
As others pointed out, you probably want to use an array or Vec<T>
instead.
正如本书所解释的,元组是异构数据类型:每个元组元素可以有不同的类型.如果您可以遍历所有元组值,可能会发生奇怪的事情:
As the book explains, tuples are heterogeneous data types: each tuple element can have a different type. If you could iterate over all tuple values, strange things could happen:
let data = (12, true);
for a in 0..data.len() {
// Oops: `+ 1` makes sense for the integer, but not for the bool
println!("{}", data.a + 1);
}
另一方面,数组是同构类型:所有元素都具有相同的类型!所以上面的代码片段中的问题不会发生.Vec
也是如此:只能存储 T
类型的元素.Vec
和数组的区别:向量可以增长,即动态调整大小,而数组在编译时具有固定大小.
On the other hand, arrays are homogeneous types: all elements have the same type! So the problem in the snippet above can't occur. The same is true for Vec<T>
: only elements of type T
can be stored. The difference between Vec<T>
and an array: a vector can grow, i.e. is dynamically sized while an array has a fixed size at compile time.
这是带有数组的代码片段(游乐场):
Here is your code snippet with an array (Playground):
let data = [12, 3, 4, 5];
for a in 0..data.len() {
println!("{}", data[a]);
}
当然,如果你愿意,你可以迭代数组之类的集合而不迭代索引(例如 for elem in &data
).
But of course, you can iterate over collections like arrays without iterating over indices, if you want (e.g. for elem in &data
).
最后一点:当然,在技术上可以通过执行 unsafe
指针魔术来创建动态元组索引 - 假设您只在元组中存储相同的类型.但这几乎没有必要,应该避免.这就是为什么我什至不会展示代码如何做到这一点.
As a last note: of course, it's technically possible to create a dynamic tuple index by doing unsafe
pointer magic – assuming you only store the same types in your tuple. But this is hardly ever necessary and should be avoided. That's why I won't even show code how to do it.
这篇关于如何制作动态索引以获取元组的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!