learn-rust

Free Rust 🦀 course in English 🇬🇧

View on GitHub

Table of contents📚

Structs🧱

What is a struct❔

Structs are a way to group related data together in a data type.

How to create a struct❔

We know that an user can have a username, and an email.

So we can create a struct to represent this data instead of having two variables.

To create a struct, we use the keyword struct and then the name of the struct capitalized.

struct User {
    username: str,
    email: str,
}

ℹ️ structs are declared outside the main function.

ℹ️ We have to specify the type of the variables inside the struct.

How to use a struct🤹

Now that we have a struct we can create an instance of it.

Imagine having an user with the username Bob 🐡 and the email bobthefish@skwal.net.

let bob = User {
    username: "Bob 🐡",
    email: "bobthefish@gmail.com",
};

We can access the values of the struct by using the dot operator struct.field :

println!("Hello, {} ! We sent you an email at {}", bob.username, bob.email);

Output:

Hello, Bob 🐡 ! We sent you an email at bobthefish@skwal.net

Modifying a struct✏️

By default, like variables, structs are immutable.

So we have to make them mutable by adding the mut keyword before the struct name when creating an instance of it.

let mut bob = User {
    username: "Bob 🐡",
    email: "bobthefish@gmail.com",
};

bob.username = "Bob 2.0 🐠";

println!("New username : {}", bob.username);

Output:

New username : Bob 2.0 🐠

Home 🏠 - Next Section ⏭️


Course created by SkwalExe and inspired by Dcode