All lessons

Lesson 8 of 11

Structs

Group related values into one type with named fields.

main.rs

struct Task {    title: String,    done: bool,}fn main() {    let mut task = Task {        title: String::from("Practice Rust"),        done: false,    };    println!("{}", task.title);    task.done = true;    println!("Done: {}", task.done);}

Program state

title type
String
done type
bool
Step 1 of 5

The Task type groups two fields. There is no task instance yet.

What’s happening

A struct defines a type by giving each field a name and a type. Here a Task holds a String title and a Boolean that tracks whether the task is done.

To create a Task, supply values for its fields. Use a dot to read a field. When the instance is bound with let mut, you can assign a new value to one field and keep the others.

Read more in The Rust Book