Open In App
Related Articles

Rust – Tuple

Improve Article
Improve
Save Article
Save
Like Article
Like

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 

 


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 18 Oct, 2022
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials