Structs, Enums and Traits

Rust Structs

Group related values into your own type with named fields.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • Defining a struct
  • Reading and changing fields
  • Struct update syntax
User
name"Ada"
age37
activetrue

Your own type with named fields

A struct is a type you define by naming its fields. It keeps related data together, such as the name, age and status of a user.

A struct value must be declared mut before a field can change. #[derive(Debug)] lets {:?} print the whole struct. ..user fills the fields that are not listed from another value, here only age.

Key points

  1. A struct value must be mut to change a field.
  2. #[derive(Debug)] lets {:?} print it.
  3. ..user copies the remaining fields.

Runnable Rust example

Rust
Run code →
main.rs
#[derive(Debug)]
struct User {
    name: String,
    age: u32,
    active: bool,
}

fn main() {
    let mut user = User {
        name: String::from("Ada"),
        age: 36,
        active: true,
    };
    user.age += 1;

    println!("{} is {}", user.name, user.age);
    println!("{:?}", user);

    let guest = User { name: String::from("Guest"), active: false, ..user };
    println!("{} {} {}", guest.name, guest.age, guest.active);
}
Get a Run button for this example Result of running the code
Ada is 37
User { name: "Ada", age: 37, active: true }
Guest 37 false

Practice

Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges