7

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.

Valencia
  • 117
  • 1
  • 6
  • 7
    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. – Caesar Feb 15 '22 at 04:39
  • @Caesar so its just "categorizing a tuple" to a form and referring that categroized tuple with a name? – Valencia Feb 15 '22 at 05:04
  • 3
    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);`.) – Caesar Feb 15 '22 at 05:10

1 Answers1

12

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
}
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187