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