Structs, Enums and Traits
Rust Structs
Group related values into your own type with named fields.
What you'll learn
- Defining a struct
- Reading and changing fields
- Struct update syntax
User
name"Ada"age37activetrueYour 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
- A struct value must be mut to change a field.
- #[
derive(Debug)] lets {:?} print it. - ..user copies the remaining fields.
Runnable Rust example
Rust
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);
}
Ada is 37
User { name: "Ada", age: 37, active: true }
Guest 37 falsePractice
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.
Your progress is saved in this browser Sign in to keep it on every device.
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