Tuples in Rust

Pascal Precht
InstructorPascal Precht
Share this video with your friends

Social Share Links

Send Tweet

Learn how to represent multiple values of different type using a single type by leveraging the power of tuples in Rust.

Instructor: [00:00] Tuples are collections of values that can have different types. To create a tuple, we write a sequence of values separated by commas, surrounded by parentheses.

[00:10] For example, we could create a variable point that represents a point in a coordinate system using a tuple like this. In this case, the tuple would be of type (i32, i32). However, it's totally possible for a tuple to have different types.

[00:29] Tuples can have more than two values as well. For example, we could say a point has an id, which in this case would be of type string. Then the tuple would become a triple of type (string, i32, i32).

[00:44] To access the values of a tuple, we would use constant indexes. In this case, we could say println!. Then we say Point placeholder, then placeholder, another_placeholder. Then we give it point.0and point.1 and point.2. When we save and run this program, we'll see it'll output Point A, 32, 34.

[01:09] Tuples are useful for cases where we want to represent multiple values of different type as a single type without necessarily introducing a new custom type. Just like any other type in Rust, a tuple can be returned from functions as well.

[01:24] For example, if we have a text of "Hello, world," we could call its split method on it, which would return a head and tail of the text. In this case, the returned value would be a tuple of type string slice reference and string slice reference.

[01:46] Tuples can hold up to 12 values. For consistency's sake, a tuple can hold a single value as well. We could have a variable a of type tuple, some_value. This would be totally valid. Notice, however, that there is a trailing comma here. This is needed in order to have Rust distinguish between this tuple expression from a simple expression such as 1 + 1.