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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With