Why is a "tuple struct" in rust called "named tuple"
Asked Answered
T

1

10

As per this

Tuple structs, which are, basically, named tuples.

// A tuple struct
struct Pair(i32, f32);

Later in the code

// 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);

If this is a "named tuple" why am I accessing it using .0 and .1? How is that different from a "normal tuple"?

let pair = (1, 0.1);
println!("pair contains {:?} and {:?}", pair.0, pair.1);

In Python a named tuple has a name and also allows access via index

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

So the question, what is the "name" in the "named tuple" in the above rust example? To me the "The classic C structs" (in the same link) is what sounds like a "named tuple" as I can access it using .x and .y if I initialised the struct (Pair) as such. I fail to understand this from the link.

Tintometer answered 15/2, 2022 at 3:59 Comment(3)
For a "named tuple", the tuple itself is named (Pair here), but its fields are anonymous. That's unlike a normal tuple, where nothing is named, and a normal ("classic") struct, where both the struct and its fields have names. And well, python does this differently. Such is life with nomenclatures.Foil
@Foil so its just "categorizing a tuple" to a form and referring that categroized tuple with a name?Tintometer
Hmm. Generally yes, but I'm not sure whether "categorizing" is the right word. A named tuple is really its own type, distinct from any other tuple or struct with fields of the same type. (Compare that e.g. with a type alias type Pair = (i32, f32);.)Foil
B
16

Tuple structs, which are, basically, named tuples.

It is not the instance or members that are named, but the type as a whole.

How is that different from a "normal tuple"?

A function that accepts a Tuple struct will not accept a regular tuple, and vice-versa.

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
}
Buskus answered 15/2, 2022 at 4:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.