Open In App

Rust – Tuple

Improve
Improve
Like Article
Like
Save
Share
Report

A tuple in rust is a finite heterogeneous compound data type, meaning it can store more than one value at once. In tuples there is no inbuilt method to add elements into a tuple. We can use the index to get the value of a tuple, and we also can not iterate over a tuple using for loop.

Tuples in Rust are defined using small brackets as shown below :

Syntax: ("geeksforgeeks", 1, 'geek')

It is important to note that tuples are a sequence in Rust. This means its elements can be accessed by the position which is also known as tuple indexing.

Example 1: Below is the rust program to get values in a tuple.

Rust




// Rust program to get value from tuple
// using index
fn main() {
    let gfg = ("cp", "algo", "FAANG", "Data Structure");
   
    // complete tuple
    println!("complete tuple = {:?} ", gfg );
   
    // first value
    println!("at 0th index = {} ", gfg.0 );
   
    // second value
    println!("at 1st index = {} ", gfg.1 );
   
    // third value
    println!("at 2nd index = {} ", gfg.2 );
   
    // fourth value
    println!("at 3rd index = {} ", gfg.3 );
}


Output : 

complete tuple = ("cp", "algo", "FAANG", "Data Structure") 
at 0th index = cp 
at 1st index = algo 
at 2nd index = FAANG 
at 3rd index = Data Structure 

Example 2: Here we will use strings and integers both in tuples. 

Rust




fn main() {
   
    // tuple with different types of values
    let gfg = ("cp", 10, "FAANG", 20);
    println!("complete tuple = {:?} ", gfg );
    println!("at 0th index = {} ", gfg.0 );
    println!("at 1st index = {} ", gfg.1 );
    println!("at 2nd index = {} ", gfg.2 );
    println!("at 3rd index = {} ", gfg.3 );
}


Output : 

complete tuple = ("cp", 10, "FAANG", 20) 
at 0th index = cp 
at 1st index = 10 
at 2nd index = FAANG 
at 3rd index = 20 

 



Last Updated : 18 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads