Skip to content
Related Articles

Related Articles

Primitive Compound Datatypes in Rust

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 03 Dec, 2021

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:

  • Arrays
  • Tuples

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.



fn main() {
    // creating tuple
    let gfg: (&str, &str, &str) = ("Geeks", "For", "Geeks");
    // accessing tuple data using positional argument
    println!("{} {} {}", gfg.0, gfg.1, gfg.2);
    // creating another tuple
    let article = ("geeksforgeeks", "kushwanthreddy", 14,12,2020);
    let (a,b,c,d,e) = article;
    // accessing tuple using variables
    println!("This article is written by {} at {} on {}/{}/{}", b,a,c,d,e);


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.



fn main() {
    // creating array
    let gfg = ["Geeks", "For", "Geeks"];
    // accessing array data using positional argument
    println!("{} {} {}", gfg[0], gfg[1], gfg[2]);


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. 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!