Skip to content

Proposal: Name annotation for tuple types #2870

@hez2010

Description

@hez2010

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions