DEV Community

Cover image for Structs in Rust
Francesco Ciulla
Francesco Ciulla

Posted on

Structs in Rust

In this lesson, we will talk about Structs in Rust

What are Structs?

Structs are a way to create more complex data types.

They are similar to tuples, but with a few differences.

For example, you can name the fields of a struct (and you can also define methods for structs).

If you prefer a video version

All the code is available on GitHub (link available in the video description)

Define a Struct

Let's say that we want to crete a User, with name, email, is_active and age. We can define a struct like this:

struct User {
    name: String,
    email: String,
    is_active: bool,
    age: u8,
}
Enter fullscreen mode Exit fullscreen mode

And then you can create an instance of the struct like this:

struct User {
    name: String,
    email: String,
    is_active: bool,
    age: u8,
}

fn main() {
    let user = User {
        name: String::from("Jhon Doe"),
        email: String::from("doe@mail.com"),
        is_active: true,
        age: 25,
    };
}
Enter fullscreen mode Exit fullscreen mode

Accessing Struct Fields

You can access the fields of a struct using dot notation:

struct User {
    name: String,
    email: String,
    is_active: bool,
    age: u8,
}

fn main() {
    let user = User {
        name: String::from("Jhon Doe"),
        email: String::from("doe@mail.com"),
        is_active: true,
        age: 25,
    };

    println!("User name: {}", user.name);
}
Enter fullscreen mode Exit fullscreen mode

Explanaition:

  • We define a struct called User with four fields: name, email, is_active and age.
  • We create an instance of the struct and assign it to the user variable.
  • We access the name field of the user struct using dot notation (user.name).

Structs in Rust - Rust programming tutorial

Mutable Structs

You can make a struct mutable by using the mut keyword:

struct User {
    name: String,
    email: String,
    is_active: bool,
    age: u8,
}

fn main() {
    let mut user = User {
        name: String::from("Jhon Doe"),
        email: String::from("doe@mail.com"),
        is_active: true,
        age: 25,
    };

    user.name = String::from("Francesco");
    println!("User name: {}", user.name);

}
Enter fullscreen mode Exit fullscreen mode

Structs in Rust - Rust programming tutorial

Note the you can't make individual fields of a struct mutable, you can only make the entire struct mutable.

Create a Struct instance using a function

You can create a function that returns a struct instance:

struct User {
    name: String,
    email: String,
    is_active: bool,
    age: u8,
}

fn main() {
    let user = create_user(String::from("Jhon Doe"), String::from("doe@mail"),);

    println!("User name: {}", user.name);
}

fn create_user(name: String, email: String,) -> User {
    User {
        name,
        email,
        is_active: true,
        age : 25,
    }
}
Enter fullscreen mode Exit fullscreen mode

You can see the init shorthand syntax in the create_user function. This is a shorthand for initializing fields with variables that have the same name as the fields.

Structs in Rust - Rust programming tutorial

Creating Instances from Other Instances with Struct Update Syntax

You can create a new instance of a struct using another instance with the struct update syntax:

struct User {
    name: String,
    email: String,
    is_active: bool,
    age: u8,
}

fn main() {
    let user1 = User {
        name: String::from("Jhon Doe"),
        email: String::from("doe@mail.com"),
        is_active: false,
        age: 40
    };

    let new_user = User {
        name: String::from("Francesco"),
        email: user1.email,
        is_active: user1.is_active,
        age: user1.age,
    };

    println!("User name: {}", new_user.name);
}
Enter fullscreen mode Exit fullscreen mode

In this example, we create a new instance of the User struct using the user1 instance with the struct update syntax.

Structs in Rust - Rust programming tutorial

Tuple Structs

Tuple structs are similar to regular structs, but their fields are not named:

struct Color(i32, i32, i32);
struct Point(i32, i32, i32);

fn main() {
    let black = Color(0, 0, 0);
    let origin = Point(0, 0, 0);
    println!("Black color: {}, {}, {}", black.0, black.1, black.2);
    println!("Origin: {}, {}, {}", origin.0, origin.1, origin.2);
}
Enter fullscreen mode Exit fullscreen mode

In this example, we define two tuple structs: Color and Point. We create instances of these tuple structs and access their fields using dot notation.

Structs in Rust - Rust programming tutorial

Unit-Like Structs

You can define a struct with no fields, called a unit-like struct:

#[derive(Debug)]
struct User;

fn main() {
    let user = User;
    println!("User: {:?}", user);
}
Enter fullscreen mode Exit fullscreen mode

Unit-like structs are useful when you need to implement a trait on a type but don't have any data to store in the type.

Structs in Rust - Rust programming tutorial

Conclusion

Structs are a way to create more complex data types in Rust. They are similar to tuples, but with a few differences. You can name the fields of a struct (and you can also define methods for structs). You can also make a struct mutable by using the mut keyword.

You can create a function that returns a struct instance. You can create a new instance of a struct using another instance with the struct update syntax. You can define tuple structs and unit-like structs.

I hope this lesson was useful. In the next lesson, we will see a practical example of using structs in Rust.

If you prefer a video version

All the code is available on GitHub (link available in the video description)

You can find me on https://francescociulla.com and on Twitter/X

Top comments (4)

Collapse
 
nigel447 profile image
nigel447

prefer this syntax to golang, content here is very useful, its a shame that the code blocks are not formatted for clarity

struct MyStruct {
name:String,
}

Collapse
 
francescoxx profile image
Francesco Ciulla

it should be fixed now, thanks

Collapse
 
sdrsdr profile image
Stoian Ivanov

Instances from other instances example is not really good! User.email is moved to new_user and if you try to use it the compiler gets engry 😃

Collapse
 
francescoxx profile image
Francesco Ciulla

There are different ways to avoid this (I explain it in the video but I didn't want to make the article too long). you can either clone() the single propery or even clone the whole instance adding the clone trait to the struct