How to use structs in RUST

What are Structs in RUST

Structs are similar to tuples. The difference between Struct and Tuple is that in Structs each piece of data has its own name so it's clear what the values mean. As a result of these names, structs are more flexible than tuples as you don't have to rely on the order of the data to specify or access the values of an instance.

Define Struct

Struct is defined with the keyword struct and name of struct. A struct's name should describe the significance of the pieces of data being grouped together. Then, inside curly brackets, we define the names and types of the pieces of data, which are called fields. For example, below is the struct that store information about a user.

   
    struct User {
        active: bool,
        username: String,
        email: String,
    }
     

In the above User struct we have 3 fields "active","username" and "email", where "active" is type bool and "username", "email" is type String.

Using Struct in RUST Program

We will use struct in below program that calculates area of a Rectangle.

Step 1: Create a file with name main.rs.

Step 2: In main.rs write below code to create Rectangle struct.

   
    struct Rectangle {
        width: u32,
        height: u32,
    }
     

Step 3: Define a function named area.

   
    fn area(rectangle: &Rectangle) -> u32 {
        rectangle.width * rectangle.height
    }
     

The area function accesses the width and height fields of the Rectangle instance and returns the calculated area.

Step 4: Define the main function.

   
    fn main() {
        let rect1 = Rectangle {
            width: 100,
            height: 10,
        };
    
        println!(
            "The area of the rectangle is {} ",
            area(&rect1)
        );
    }
     

In this main function we created an instance of the Rectangle struct and passed it to area function.

Step 5: Compile the program.

   
    rustc main.rs
     

Step 6: Execute the program.

   
    .\main.exe
     

Output

   
    The area of the rectangle is 1000 
     

Complete code snippet for main.rs.

   
    struct Rectangle {
        width: u32,
        height: u32,
    }
    
    fn area(rectangle: &Rectangle) -> u32 {
        rectangle.width * rectangle.height
    }
    
    
    fn main() {
        let rect1 = Rectangle {
            width: 100,
            height: 50,
        };
    
        println!(
            "The area of the rectangle is {} square pixels.",
            area(&rect1)
        );
    }        
     

Category: RUST