A tuple is a collection of values that can be of different types.
βΉοΈ Tuples are usually used to return multiple values from a function.
βΉοΈ Tuples can contain other tuples.
A tuple can be declared with the following syntax:
let zoo = ("π¦ Gorilla", "π¦ Fox", "π¦ Zebra", "π Elephant");
We can access different values in a tuple with the following syntax: tuple.index
Example, print the first value in the tuple:
let zoo = ("π¦ Gorilla", "π¦ Fox", "π¦ Zebra", "π Elephant");
println!("The first animal in the zoo is the ", zoo.0);
Output:
The first animal in the zoo is the π¦ Gorilla
We can extract values from a tuple and store them in variables with the following syntax:
let zoo = ("π¦ Gorilla", "π¦ Fox", "π¦ Zebra", "π Elephant");
let (a, b, c, d) = zoo;
println!("In the zoo, there is a {}, a {}, a {}, and an {}", a, b, c, d);
Output:
In the zoo, there is a π¦ Gorilla, a π¦ Fox, a π¦ Zebra, and an π Elephant
Home π - Next Section βοΈ