Chooce video playback speed
speed:1

Tuples in Rust

InstructorPascal Precht

Share this video with your friends

Send Tweet

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

This lesson is a Community Resource

A Community Resource means that it’s free to access for all. The instructor of this lesson requested it to be open to the public.

Instructor: 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.

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.

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

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.

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.

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.

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.