Structs in Rust
Tags: rust, webdev, beginners, tutorial
Published: 2024-03-12 14:04:16

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
{% youtube PCjuO-Bv5FI %}

<!-- <iframe width="905" height="510" src="https://www.youtube.com/embed/PCjuO-Bv5FI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> -->

All the code is available on [GitHub](https://youtu.be/PCjuO-Bv5FI) (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:

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

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

```rust
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,
    };
}
```


## Accessing Struct Fields

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

```rust
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);
}
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p8ftlzr2b3kmjc94d05x.png)](https://youtu.be/PCjuO-Bv5FI)

## Mutable Structs

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

```rust
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);

}
```

[![Structs in Rust - Rust programming tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o0d3ealwd1pabinrls47.png)](https://youtu.be/PCjuO-Bv5FI)

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:

```rust
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,
    }
}
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l69dzuu8lyl4mxo5ubxf.png)](https://youtu.be/PCjuO-Bv5FI)

## 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:

```rust
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);
}
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/28qkv2lwc0fdkyxqbuzd.png)](https://youtu.be/PCjuO-Bv5FI)

## Tuple Structs

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

```rust
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);
}
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/itkr4dg71exrfdes91fs.png)](https://youtu.be/PCjuO-Bv5FI)

## Unit-Like Structs

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

```rust
#[derive(Debug)]
struct User;

fn main() {
    let user = User;
    println!("User: {:?}", user);
}
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rn23cig9vdd1armfg13.png)](https://youtu.be/PCjuO-Bv5FI)

## 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
{% youtube PCjuO-Bv5FI %}

<!-- <iframe width="905" height="510" src="https://www.youtube.com/embed/PCjuO-Bv5FI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> -->

All the code is available on [GitHub](https://youtu.be/PCjuO-Bv5FI) (link available in the video description)

You can find me on https://francescociulla.com and on [Twitter/X](https://twitter.com/FrancescoCiull4)