Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do tuples implement `Copy`?

Tags:

tuples

rust

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.)?

like image 874
Zarni Phyo Avatar asked Aug 23 '17 18:08

Zarni Phyo


1 Answers

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.

  • Clone
  • Copy
  • PartialEq
  • Eq
  • PartialOrd
  • Ord
  • Debug
  • Default
  • Hash

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.

like image 93
Sam Estep Avatar answered Sep 28 '22 01:09

Sam Estep