How To Use Structure In Rust?

Introduction

Rust is a modern, systems-level programming language that offers a high level of control over low-level details, making it ideal for systems programming, game development, and other performance-critical applications. One of Rust's core features is its support for structures, also known as structs. 

In this article, we learn about Structure in Rust programming language. Structures, or "structs," are fundamental features in Rust that allow you to define custom data types with named fields. They are similar to structs in other programming languages, such as C and C++ but with some unique features due to Rust's emphasis on safety and concurrency.

What is a structure in Rust?

In Rust, a structure is a user-defined data type that allows you to group related values. Structures are similar to classes in other programming languages but have some important differences.

struct Point {
    x: f32,
    y: f32,
}

This defines a struct called Point with two fields, and y, which are f32 (32-bit floating-point) values.

How to create a structure in Rust?

In Rust, defining a struct is simple. Here's an example of defining a simple Employee struct.

struct Employee{
    employee_fname:String,
    employee_lname:String,
    employee_mail:String,
    password:String,
    user_type:i64,
    employee_id:i64
 }

In this example, we define an Employee struct with six fields: three String names, employee_fname,employee_lname, and employee_mail. And two i64 (signed 64-bit integer)  user_type and employee_id.It's worth noting that, unlike in other languages, the fields in a Rust struct are private by default, which means they can only be accessed within the same module.

Create an instance of Employee structure

You can create Employee struct instances and initialize their fields as follows-

// Create an instance of the struct
let Employee1 = Employee {
    employee_fname: String::from("shaily"),
    employee_lname: String::from("dubey"),
    employee_mail: String::from("[email protected]"),
    user_type:2
    employee_id: 101,
    };

In this example, we create an Employee struct instance called Employee1 and populate its fields with values using a struct literal. The String::from function creates a String object with the specified value, which is then assigned to the struct's corresponding fields.

Mutable structs

In Rust, structs can be made mutable by using the mut keyword. This allows you to modify the values of the struct's fields after it has been created.

let mut person2 = Person {
    name: String::from("Bob"),
    age: 30,
    email: String::from("[email protected]"),
};
person2.age = 31;

This creates a mutable instance of the Person struct called person2 and modifies its age field to 31.

How to access the fields of a structure?

Like regular variables, you can access the fields of a struct by using dot notation (.) followed by the field name.

struct Employee{
    employee_fname:String,
    employee_lname:String,
    employee_mail:String,
    password:String,
    user_type:i64,
    employee_id:i64
 }
// Access the fields of the struct
fn main(){
println!("employee_first_name: {}", person1.employee_fname);
println!("employee_last_name: {}", person1.employee_lname);
println!("employee_email: {}", person1.employee_mail);
println!("employee_id: {}", person1.employee_id);
println!("user_type: {}", person1.user_type);
}

In this example, we use the println! macro to access the fields of the employee1 struct and print their values.

How to define a method in a structure?

Structs can also have methods, which are functions that operate on the struct's instances. Here's an example of defining and using methods on a struct.

// Define a struct
struct Rectangle {
    width: u32,
    height: u32
}
// Implement methods on the struct
impl Rectangle {
    // Method to calculate the area of the rectangle
    fn area(&self) -> u32 {
        self.width * self.height
    }
// Method to check if the rectangle is a square
    fn is_square(&self) -> bool {
        self.width == self.height
    }
}

This example defines a Rectangle struct with width and height fields. We then implement two methods on the struct using the impl block. The area method calculates the area of the rectangle by multiplying its width and height, and the is_square method checks if the rectangle is a square by comparing its width and height.

How do we call methods on an instance of structure?

You can call the methods on instances of the Rectangle struct using dot notation (.) followed by the method name.

// Create an instance of the struct
let rect1 = Rectangle { width: 10, height: 20 };
// Call the methods on the struct
println!("Area: {}", rect1.area());
println!("Is Square: {}", rect1.is_square());

In this example, we create an instance of the Rectangle struct called rect1 and call its area and is_square methods to calculate and print the area and determine if it's a square, respectively.

Conclusion

Rust's struct feature allows you to define custom data types with named fields, and you can use it. Rust's structs are a powerful feature allowing you to group related values into custom data types. With structs, you can create instances of your data types and access them.


Similar Articles