struct - 为什么 rust 中的 "tuple struct"称为 "named tuple"

标签 struct rust tuples

根据 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/

相关文章:

rust - 使用 .unwrap() 应该被视为不好的做法吗?

rust - 匹配枚举字符串

module - 将结构移动到一个单独的文件而不拆分成一个单独的模块?

python - Pandas Dataframe 到元组字典

c++ - 微型 C++ 结构的行为

swift - 在 Swift 中使用 Objective-C 结构时出错(无法在范围内找到类型 'XXX')

C 具有结构的双向链表

c - 这两个陈述有什么区别?

typescript - 如何确保元组元素标签被保留?

c# - C# 方法可以定义可变数量的对象参数和可变数量的整数参数吗?