Mastering Rust Data Types: A Comprehensive Guide for Developers

Array Data Types In Rust

An array is list of elements of the same types. For example if we shortage to store the first five natural numbers, we can make an array instead of creating five severals variables.

In Rust Program, we can use the square brackets [] to make an array.

// array of natural numbers
let arr = [1, 2, 3, 4, 5];

Above, we have created an array named arr that was five numbers.

Creating an Array in Rust Programming

In Rust Program, we can make an array in three severals ways:

  • Array with data types
  • Array without data types
  • Array with default values Let’s fell each of these array nature methods in detail.

Array with Data Types in Rust Program

fn main() {
    // initialization of array with data type
    let numbers: [i32; 5] = [1, 2, 3, 4, 5];
    
    println!("Array of numbers = {:?}", numbers);
}

Output :

Array of numbers = [1, 2, 3, 4, 5]

In the upon example, we have maked an array of numbers with the evolution,

let numbers: [i32; 5] = [1, 2, 3, 4, 5];

Above,

  • numbers - name of array
  • [i32; 5] - i32 is the of predefined data type of array elements and 5 is the size of the array
  • [1, 2, 3, 4, 5] - elements under the array

Array without Data Types in Rust Program

fn main() {
    // initialization of array without data type
    let numbers = [1, 2, 3, 4, 5];
    
    println!("array of numbers = {:?}", numbers);
}

Output :

Array of numbers = [1, 2, 3, 4, 5]

In above example, you have maked an array of numbers with the evolution,

let numbers = [1, 2, 3, 4, 5];

Above,

  • numbers - name the array
  • [1, 2, 3, 4, 5] - element under the array

Array with Default Values in Rust Program

fn main() {
    // initialization of array with default values
    let numbers: [i32; 5] = [3; 5];
    
    println!("Array of numbers = {:?}", numbers);
}

Output :

Array of numbers = [3, 3, 3, 3, 3]

Please see the above example, you have created an array of numbers with the evolution,

let numbers: [i32; 5] = [3; 5];

Above,

  • numbers - name the array
  • [i32; 5] - illustrates the data type (i32), and size (5) of the array
  • [3; 5] - is a revolving evolution, here the value 3 will fullfill the array 5 times

Different Ways to Create Array in Rust Program

fn main() {
    // an array without data type
    let a = [5, 4, 3, 2, 1];
    
    // an array with data type and size
    let b: [i32; 5] = [1, 2, 3, 4, 5];
    
    // an array with default values
    let c = [3; 5];
    
    println!("a = {:?}", a);
    println!("b = {:?}", b);
    println!("c = {:?}", c);
}

Output :

a = [5, 4, 3, 2, 1]
b = [1, 2, 3, 4, 5]
c = [3, 3, 3, 3, 3]

Access Elements of Rust Program Array

Each element in an array is connected with a unique rank of numbers. This number is aware of as the array index.

Remember we have an array of colors

let colors = ["red", "green", "blue"];

Example: Access Array Elements In Rust

fn main() {
    let colors = ["red", "green", "blue"];
    
    // accessing element at index 0
    println!("1st Color: {}", colors[0]);

    // accessing element at index 1
    println!("2nd Color: {}", colors[1]);

    // accessing element at index 2
    println!("3rd Color: {}", colors[2]);
}

output :

1st Color: red
2nd Color: green
3rd Color: blue

Mutable Array in Rust Program

In Rust Program, an array is immutable, that means we cannot alternative its elements once it is created.

We can create a mutable array by using the mut keyword before imposing it to a variable. For example-

// create a mutable array in rust
let mut numbers: [i32; 5] = [1, 2, 3, 4, 5];

Now, we can make alternative to this array.

Now Let’s make a look at an example,

fn main() {
    let mut numbers: [i32; 5] = [1, 2, 3, 4, 5];
    
    println!("original array = {:?}", array);
    
    // change the value of the 3rd element in the array
    numbers[2] = 0;
    
    println!("changed array = {:?}", numbers);
}

Output :

original array = [1, 2, 3, 4, 5]
changed array = [1, 2, 0, 4, 5]

Above, we have imposed a new value of 0 to the third element in the array.

numbers[2] = 0;

We alternative the element at index 2 (third element) from 3 to 0. This is easy to because we have created the numbers array as mutable.

Looping With an Array in Rust Program

In Rust Program, You can use the for..in loop to iterate With an array. For example-

fn main() {
    let colors = ["red", "green", "blue"];
    
    // loop through an array to print its index and value
    for index in 0..3 {
        println!("Index: {} -- Value: {}", index, colors[index]);
    }
}

Output :

Index: 0 -- Value: red
Index: 1 -- Value: green
Index: 2 -- Value: blue

Please see the above example, you have used the for...in loop with range 0..3.

for index in 0...3 {
    ...
}

Rust Slice In Rust Program

A Rust Program slice is a data types used to access sections of data stored in collections like arrays, vectors and strings.

Guess we have an array,

let numbers = [1, 2, 3, 4, 5];

If we want to extractive the 2nd and 3rd elements of this array. You can slice the array like as this-

let slice = &array[1..3];

Above, we let’s look at the right-hand side of the evolution,

  • &numbers - marks a mention to the variable numbers (not the actual value)
  • [1..3] - is a modulator for slicing the array from start_index 1 (inclusive) to end_index 3 (exclusive)

Example: Slice In Rust

fn main() {
    // an array of numbers
    let numbers = [1, 2, 3, 4, 5];
    
    // create a slice of 2nd and 3rd element
    let slice = &numbers[1..3];
    
    println!("array = {:?}", numbers);
    println!("slice = {:?}", slice);
}

Output :

array = [1, 2, 3, 4, 5]
slice = [2, 3]

Omit Indexes of a Slice In Rust

When slicing a data collection, Rust accept us to omit other the start index or the end index or both from its syntax.

&variable[start_index..end_index];

Now we see for a example

1. Omitting the Start Index of a Slice In Rust

fn main() {
    let numbers = [1, 2, 3, 4, 5];

    // omit the start index
    let slice = &numbers[..3];

    println!("array = {:?}", numbers);
    println!("slice = {:?}", slice);
}

Output :

array = [1, 2, 3, 4, 5]
slice = [1, 2, 3]

Above example, &numbers[..3] includes ..3 outside of the start index. that means the slice starts from index 0 and get up to index 3 (exclusive). It is equiponderant to &numbers[0..3].

2. Omitting the End Index of a Slice In Rust

fn main() {
    let numbers = [1, 2, 3, 4, 5];

    // omit the end index
    let slice = &numbers[2..];

    println!("array = {:?}", numbers);
    println!("slice = {:?}", slice);
}

Output :

array = [1, 2, 3, 4, 5]
slice = [3, 4, 5]

3. Omitting both Start and End Index of a Slice In Rust

fn main() {
    let numbers = [1, 2, 3, 4, 5];
    
    // omit the start index and the end index
    // reference the whole array
    let slice = &numbers[..];

    println!("array = {:?}", numbers);
    println!("slice = {:?}", slice);
}

output :

array = [1, 2, 3, 4, 5]
slice = [1, 2, 3, 4, 5]

Above, &numbers[..] includes .. outside of the start and end index. This means the slice starts from index 0 and gets up to index 5 (exclusive).

The Mutable Slice in Rust Program

We can make a mutable slice by manage the &mut keyword.

let numbers = [1, 2, 3, 4, 5];
let slice = &mut numbers[1..4];

At one time the slice is checked as mutable, we can make values under the slice. Now Let’s see an example-

fn main() {
    // mutable array
    let mut colors = ["red", "green", "yellow", "white"];
    
    println!("array = {:?}", colors);

    // mutable slice
    let sliced_colors = &mut colors[1..3];
    
    println!("original slice = {:?}", sliced_colors);

    // change the value of the original slice at the first index
    sliced_colors[1] = "purple";

    println!("changed slice = {:?}", sliced_colors);
}

Output :

array = ["red", "green", "yellow", "white"]
original slice = ["green", "yellow"]
changed slice = ["green", "purple"]

Rust Tuple In Rust Program

A tuple in Rust program accommodate us to store values of several data types. For example-

let tuple = ('Hello', 5, 3.14);

Above, You have used the small bracket ( ) to make a tuple and it’s efficient to store a string value, Hello, an integer value, 5, also a floating-point value 3.14 together.

Making a Tuple in Rust

In Rust Program, we can make a tuple in two several ways:

  • Tuple with data types
  • Tuple without data types

Rust Tuple with Data Type In Rust program

When making a tuple, you can notice the type of data it is storing. For example-

// create a tuple with data type
let student_info: (&str, u8, f32) = ("Ricky", 21, 3.56);

Below,

  • let student_info: (&str, u8, f32) - marks the variable name and the data types of the tuple climate
  • ("Ricky", 21, 3.56) - marks the climate of the tuple

Example: Tuple with Data Type In Rust

fn main() {
    // initialization of tuple with data type
    let tuple: (&str, f32, u8) = ("Rust", 3.14, 100);
    
    println!("Tuple contents = {:?}", tuple);
}

Output :

Tuple contents = ("Rust", 3.14, 100)

Tuple without Data Type in Rust Program

You can make a tuple without notice the type of data it is storing. The Rust compiler can automatically discover and set the data type. For example-

// create a tuple without data type
let student_info = ("Ricky", 21, 3.56);

Example: Tuple without Data Types In Rust

fn main() {
    // initialization of tuple without data type
    let tuple = ("Rust", "fun", 100);

    println!("Tuple contents = {:?}", tuple);
}

Output :

Tuple contents = ("Rust", "fun", 100)

Accessing Elements in a Tuple In Rust Program

Every element in a tuple is associated with a single sequence of numbers. This number is as known as the tuple index or just** index**.

We have a tuple

let random_tuple = ("Hello", 200, 3.14);

Example: Access Tuple Elements In Rust Program

fn main() {
    let random_tuple = ("Hello", 200, 3.14);

    // accessing tuple element at index 0
    println!("Value at Index 0 = {}", random_tuple.0);
    
    // accessing tuple element at index 1
    println!("Value at Index 1 = {}", random_tuple.1);
    
    // accessing tuple element at index 2
    println!("Value at Index 2 = {}", random_tuple.2);
}

Output :

Value at Index 0 = Hello
Value at Index 1 = 200
Value at Index 2 = 3.14

Mutable Tuple In Rust Program

In Rust Program, a tuple is immutable, that means you cannot make its elements once it is created.

Still, you can create a mutable array by using the mut keyword in the past assigning it to a variable. For example-

// create a mutable tuple 
let mut mountains = ("Everest", 8848, "Fishtail", 6993);

So, we can make changes in this tuple.

Now take a example-

fn main() {
    // initialize a mutable tuple
    let mut mountain_heights = ("Everest", 8848, "Fishtail", 6993);
    
    println!("Original tuple = {:?}", mountain_heights);
    
    // change 3rd and 4th element of a mutable tuple
    mountain_heights.2 = "Lhotse";
    mountain_heights.3 = 8516;
    
    println!("Changed tuple = {:?}", mountain_heights);
}

Output :

Original tuple = ("Everest", 8848, "Fishtail", 6993)
Changed tuple = ("Everest", 8848, "Lhotse", 8516)

Rust Struct In Rust program

Rust structs or structures are user-defined data types used to store several types of data together.

Gaze you want to store a person’s name, age, and height. For do this you can create variables for every property/field.

let personName: String = String::from("John Doe");
let personAge: u8 = 18;
let personHeight: u8 = 178;

The problem with this obtainment is we have to sustain all these variables separately. To store this fields for more than one person, you will have to create several variables for every person.

Instead, you can make a struct to store all the fields together as a single unit. For example-

struct Person {
    name: String,
    age: u8,
    height: u8
}

Defining a Struct in Rust Programming

In Rust Programming, we can use the struct keyword to define a structure. The syntax of a structure is below-

struct struct_name {
    field1: data_type,
    field2: data_type,
    field3: data_type
}

Below-

  • struct - keywords to define a structure
  • struct_name - name of structure
  • field1: data_type/field2: data_type - name and data types of the fields under the struct.

Now, see an example-

struct Person {
    name: String,
    age: u8,
    height: u8
}

Below, you have defined a structure named Person. It take on three fields:

  • name - with data types String
  • age - with data types u8
  • height - with data types u8

Instantiating Rust Struct In Rust programming

For use a structure in Rust, we can first have to create an example of structures. Now For example-

// define a structure
struct Person {
    name: String
    age: u8,
    height: u8
}

// create an instance of Person struct
let person1 = Person {
    ...
};

Accessing Fields of a Struct In Rust programming

You can use the struct instance toward with the dot . notation to access values of the fields in a structure. For example-

fn main() {
    // define a Person struct
    struct Person {
        name: String,
        age: u8,
        height: u8
    }
    
    // instantiate Person struct
    let person = Person {
        name: String::from("Akash"),
        age: 18,
        height: 178
    };
    
    // access value of name field in Person struct
    println!("Person name = {}", person.name);

    // access value of age field in Person struct
    println!("Person age = {}", person.age);

    // access value of height field in Person struct
    println!("Person height = {}", person.height);
}

Output :

Person name = Akash
Person age = 18
Person height = 178
Previous
A Comprehensive Guide to Rust for, while, and loop Constructs
Next
Deep Dive into Rust Functions, Variable Scope, and Closures