Rust programming language has a concept of compound data types which collections that can group multiple types into one. In simple words, compound Datatypes are data structures that can hold multiple data elements in a single variable (or) reference. There are two primitive compound types in Rust:
The Tuple Type:
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 index to get the value of a tuple, and we also can not iterate over a tuple using for loop, unlike arrays which are mutable, meaning once declared they cannot grow or shrink.
Example:
Rust
fn main() {
let gfg: (&str, &str, &str) = ( "Geeks" , "For" , "Geeks" );
println!( "{} {} {}" , gfg.0, gfg.1, gfg.2);
let article = ( "geeksforgeeks" , "kushwanthreddy" , 14,12,2020);
let (a,b,c,d,e) = article;
println!( "This article is written by {} at {} on {}/{}/{}" , b,a,c,d,e);
}
|
Output:
Geeks For Geeks
This article is written by kushwanthreddy at geeksforgeeks on 14/12/2020
The Array Type:
Arrays are the same as tuples but the difference is that Arrays can have multiple values of the same data type whereas tuples can have multiple values of multiple data types. Arrays in Rust are different from arrays in some other languages because arrays in Rust have a fixed length, like tuples. the array are written as a comma-separated list inside square brackets.
Example:
Rust
fn main() {
let gfg = [ "Geeks" , "For" , "Geeks" ];
println!( "{} {} {}" , gfg[0], gfg[1], gfg[2]);
}
|
Output:
Geeks For Geeks
In many low-level languages when you provide an incorrect index, invalid memory can be accessed. Rust protects you against this kind of error by immediately exiting instead of allowing memory access and continuing.
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 :
03 Dec, 2021
Like Article
Save Article