根据 this
Tuple structs, which are, basically, named tuples.
// A tuple struct
struct Pair(i32, f32);
代码后面
// Instantiate a tuple struct
let pair = Pair(1, 0.1);
// Access the fields of a tuple struct
println!("pair contains {:?} and {:?}", pair.0, pair.1);
如果这是一个“命名元组”,为什么我要使用 .0
和 .1
访问它?这与“普通元组”有何不同?
let pair = (1, 0.1);
println!("pair contains {:?} and {:?}", pair.0, pair.1);
在 Python 中,命名元组具有名称,并且还允许通过索引访问
from collections import namedtuple
Pair = namedtuple('Pair', ['x', 'y'])
pair = Pair(1, 0.1)
print(pair[0], pair[1]) # 1 0.1
print(pair.x, pair.y) # 1 0.1
那么问题来了,上面 rust 示例中“命名元组”中的“名称”是什么?对我来说,“经典 C 结构”(在同一个链接中)听起来像“命名元组”,因为我可以使用 .x
和 .y
访问它,如果我这样初始化了结构(Pair
)。我无法从链接中理解这一点。
最佳答案
Tuple structs, which are, basically, named tuples.
命名的不是实例或成员,而是整个类型。
How is that different from a "normal tuple"?
接受 Tuple 结构的函数将不接受常规元组,反之亦然。
struct Named(f32,i32);
fn accepts_tuple(t:(f32,i32)) { todo!(); }
fn accepts_named(t:Named) { todo!(); }
fn main() {
let t = (1.0f32, 1i32);
accepts_tuple(t); // OK
// accepts_named(t); // Does not compile
let n=Named(1.0f32, 1i32);
// accepts_tuple(n); // Does not compile
accepts_named(n); // OK
}
关于struct - 为什么 rust 中的 "tuple struct"称为 "named tuple",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71120973/