Learn Rust Tuple using step by step example.

A Tuple is an immutable fixed-size collection of values.

Example 1: Hello Tuple

This example will introduce you Tuples.

Step 1: Create Project

The first step is to create a Rust project .

Creating a Project Directory

Open a terminal and enter the following commands to make a projects directory and an inner directory for this example within that projects directory.

For Linux, macOS, and PowerShell on Windows, enter this:

$ mkdir ~/projects
$ cd ~/projects
$ mkdir your_example_name
$ cd your_example_name

For Windows CMD, enter this:

> mkdir "%USERPROFILE%\projects"
> cd /d "%USERPROFILE%\projects"
> mkdir your_example_name
> cd your_example_name

Step 2: Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Create a file main.rs and add the following code:

main.rs

fn main() {

    let tuple0 = ();
    println!("{:?}", tuple0);

    let mytup: (i32, i32, f64) = (10, 20, 30.0);
    match mytup {
        (a, b, c) => println!("{}", a + b + (c as i32))
    }

    let tuple1 = (5i32, 6i32);
    let (first, _) = tuple1;
    println!("{}", first);
}

If you run the code you will get the following:

()
60
5

Run

Save the code and run your code as follows:

Assuming our file name is main.rs, first compile it

$ rustc main.rs

then run it:

$ ./main

On Windows, enter the command .\main.exe instead of ./main:

compile:

> rustc main.rs

then run it:

> .\main.exe

Categorized in: