10

In the Rust Book, Chapter 18, they give an example of a tuple in pattern matching.

fn print_coordinates(&(x, y): &(i32, i32)) {
    println!("Current location: ({}, {})", x, y);
}

fn main() {
    let point = (3, 5);
    print_coordinates(&point);   // point passed as reference
}

Out of curiosity, I tried without passing as a reference like this.

fn print_coordinates((x, y): (i32, i32)) {
    println!("Current location: ({}, {})", x, y);
}

fn main() {
    let point = (3, 5);
    print_coordinates(point);   // point passed as value
    print_coordinates(point);   // point is still valid here
}

It compiles and prints out the coordinates 2 times.

Can tuples be passed into functions just like other primitive data types (numbers, booleans, etc.)?

Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
Zarni Phyo
  • 105
  • 1
  • 8
  • Highly relevant: [Do all primitive types implement the Copy trait?](https://stackoverflow.com/q/41413336/155423) – Shepmaster Aug 23 '17 at 19:11

1 Answers1

13

Yes; according to the docs, this is true for tuples of arity 12 or less:

If every type inside a tuple implements one of the following traits, then a tuple itself also implements it.

Due to a temporary restriction in Rust's type system, these traits are only implemented on tuples of arity 12 or less. In the future, this may change.

Sam Estep
  • 12,974
  • 2
  • 37
  • 75
  • Thank you for the quick answer. – Zarni Phyo Aug 23 '17 at 19:30
  • If the arity is above 12, your tuple is probably pretty bulky, e.g. `i128` of size 12 already takes 192 bytes, so it indeed doesn't make sense to try to copy a tuple such large (not to mention that there shouldn't be such enormous tuples in the first place; use an array instead) – SOFe Jul 23 '19 at 15:45