Rust Lang

Rust Structs

A struct refers to a custom or user-defined type. Structs are very useful as they allow us to store attributes of different types. The best way to think of structs is blueprints containing global attributes which can be customized to create unique objects.

For example, we can create a struct that represents users. Every user will have a username, email, and status. We can then model each entity for each from this struct.

Let us learn how we can work with structs in Rust.

Rust Define Struct

In Rust, we can define a struct using the keyword struct trailed by the name of the struct. Next, we create the struct body inside a pair of curly braces.

We can set unique properties with their corresponding data types inside the struct.

The syntax can be illustrated as shown:

structStructName {
    // struct body
    attribute_name: type,
    attribute_name: type
}

Consider the example below that creates a user struct.

structUsers {
    username: String,
    email: String,
    active: bool,
}
fnmain() {
//
}

The code above creates a user struct with username, email, and active properties.

Rust Initialize Struct

Once we have a struct defined, we can create objects from it. Creating an object from a struct is known as creating an instance of a struct.

We can create an instance of a struct by creating a variable of the struct type. An example is as shown below:

struct Users {
    username: String,
    email: String,
    active: bool,
}
fnmain() {
    let user1 = Users {
        username: "z3roday".to_string(),
        email: "[email protected]".to_string(),
        active: true
    };
}

In the main function above, we create an instance of the struct called user1. We then set unique values for the specified properties of the struct.

Note that we use a colon instead of the assignment operator to set the values for the struct instance.

Retrieve Struct Values

We can retrieve the members of a struct using the dot notation. We start by calling the name of the struct, followed by a dot and the name of the struct property we wish to access.

An example is as shown:

struct Users {
    username: String,
    email: String,
    active: bool,
}
fn main() {
    let user1 = Users {
        username: "z3roday".to_string(),
        email: "[email protected]".to_string(),
        active: true
    };
if user1.active {
println!("Account details: \n\tusername: {}\n\temail: {}", user1.username, user1.email);
    }
}

The example code above demonstrates how to access values of a struct using the dot notation. The code above should return output as:

Account details:

username: z3roday

email: zero@day.io

Rust Update Struct Values

To update the value of a struct instance, we need to make sure that the struct is mutable. Rust does not allow you to set specific fields as mutable.

Take the user1 instance. We can change the email value as shown below:

    let mut user1 = Users {
        username: "z3roday".to_string(),
        email: "[email protected]".to_string(),
        active: true
    };
    user1.email = "[email protected]".to_string();

The code above sets the user1 instance to mutable using the mut keyword. We can then access the properties of a struct a set a new value using the assignment operator.

Struct Methods

We can create methods for a struct using the impl keyword. Struct functions, also known as methods, are available to the instances of a struct.

An example is as shown:

struct Users {
    username: String,
    email: String,
    active: bool,
}
impl Users {
fnread_mail(self) {
ifself.active {
println!("You have mail");
        }
    }
}
fn main() {
    let mut user1 = Users {
        username: "z3roday".to_string(),
        email: "[email protected]".to_string(),
        active: true
    };
    user1.read_mail();
}

In the program above, we define a method called read_mail that accepts self. The self keyword in Rust allows us to refer to the instance of the struct calling that method.

We can then access the properties of the struct using the self-parameter, as shown in the example above.

We check if the user is active and return a message if true for our example.

We can call the method using the instance_of_struct.method_name();

Conclusion

This article explored how we can create and use struct in Rust. Structs allow us to define custom types and create unique objects from the defined struct types.

Thanks for reading!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list