-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Open
Description
Background
Here're ways to access tuple element in Rust for now:
let x: (i32, f64, u8) = (500, 6.4, 1);
// first
let (a, b, c) = x;
println!("{} {} {}", a, b, c);
// second
println!("{} {} {}", x.0, x.1, x.2);
The first approach is a deconstruct process, which deconstruct the tuple x
into a
, b
and c
.
The second approach is to access elements in the tuple x
directly.
However, when we use a tuple, it's hard to know meaning of its elements without comments or documents, and things like .0
are hard to distinguish if you lack acknowledge of a tuple.
Proposal
I proposed name annotation for tuple types:
let x: (count: i32, price: f64, type: u8) = (500, 6.4, 1);
And then we can access elements in the tuple x
in this way:
println!("{} {} {}", x.count, x.price, x.type);
It's more intuitive and convenient.
Note that count
, price
and type
are just name annotations for the tuple type, and they don't change the actual type (i32, f64, u8)
. x.count
will be compiled to x.0
.
Name resolving
Names are resolved as ways they're declared.
fn bar(v: (a: i32, b: bool)) -> (x: i32, y: bool) {
v.a // ok
v.b //ok
v.u // error, v wasn't declared u
v.v // error, v wasn't declared v
return v;
}
fn main() {
let tup: (u: i32, v: bool) = (5, false);
let mut result = bar(tup);
result.x // ok
result.y // ok
result.a // error, result wasn't declared a
result.b // error, result wasn't declared b
result.u // error, result wasn't declared u
result.v // error, result wasn't declared v
result = tup;
result.x // ok
result.y // ok
result.u // error, result wasn't declared u
result.v // error, result wasn't declared v
}
Nickpofig, TheRawMeatball, Corallus-Caninus, jerielverissimo, TeoBernier and 12 moreH2CO3, oovm, Nemikolh and konsumlammshepmaster, iago-lito, hadronized, mcarton, H2CO3 and 3 moreaiden-leong and eflukx
Metadata
Metadata
Assignees
Labels
No labels