Let us dive deep and learn how we can work with tuples in Rust.
Rust Create Tuple
In rust, we create a tuple by using a pair of parentheses. There are two fundamental ways to create a tuple in Rust:
- Without Type inference.
- Without type inference.
The syntax below illustrates how to create a tuple without type inference:
The second method to create a tuple is one where we infer the type.
Although the above method of tuple creation is supported, it tends to be confusing at first use.
An example of a tuple without type inference is as shown below:
let tuple = (1,2,3,4,5, "a,","b","c");
}
The above creates a tuple of different types without type inference. The compiler will automatically assign the types to the elements of the tuple.
Consider the example below that shows how to create a tuple with type inference.
In the example syntax above, we explicitly tell the compiler about the type of values we wish to store. Remember that the order is important, and each element must correspond with the defined type.
We can print a tuple using the debug trait from the std::fmt module. An example is as shown:
let tuple = (1,2,3,4,5, "a,","b","c");
println!("{:?}", tuple);
}
The program above returns the elements of the tuple:
Rust Access Tuple Elements
To access an element of a tuple, we use its corresponding index. In Rust, a tuple indexing starts at 0.
The syntax for accessing an element at a specific index is as shown:
In Rust, we use the dot notation to access an element at a specific index. This is because a tuple is technically a struct in Rust.
Consider the example below that accesses an element at index 5 in the tuple.
let tuple = (1,2,3,4,5, "a,","b","c");
// let tuple2:(i32, &str) = (1, "a");
println!("{:?}", tuple.5);
}
The program returns the element at index 5; in this case, it returns “a”.
HINT: Tuples do not allow looping. Hence, we cannot use a feature such as a for loop to iterate over each item in the tuple.
Rust Tuple Unpacking
Rust allows you to unpack the elements of a tuple into individual values. We can do this using the syntax shown below:
An example of tuple unpacking is shown below:
let tuple = (20, "Aaron", 131000);
let (age, name, salary ) = tuple;
println!("Name: {}\nAge: {}\nSalary: {}\n", name, age, salary)
}
The above example unpacks the elements into individual variables. This is a very useful feature that allows you to use specific elements of a tuple individually.
Conclusion
This guide explores how to work with tuples and tuple types in the Rust programming language. Rust treats tuples differently from other programming languages, such as Python. Check the documentation to explore more.
Thanks for reading & Happy Coding!!