Rust Fundamentals · 15 XP Pro
Defining structs
A struct groups related values under named fields. You declare the shape once and then create instances of it:
pub struct Book {
pub title: String,
pub pages: u32,
}
let b = Book { title: String::from("Rust"), pages: 300 };
println!("{}", b.pages);
Two conveniences are worth knowing:
- Field init shorthand: when a variable has the same name as the field you
can write
Book { title, pages }instead ofBook { title: title, pages: pages }. - Struct update syntax:
Book { pages: 400, ..old }builds a new value, taking every field you did not list fromold. Fields that are notCopy(likeString) are moved out ofold.
Your task
The tests build and read your struct, so it and its fields must be pub.
- Define
pub struct Playerwith public fieldsname: String,level: u32andhealth: i32. - Write
pub fn new_player(name: String, level: u32) -> Playerthat starts withhealthof100. Use field init shorthand fornameandlevel. - Write
pub fn level_up(p: Player) -> Playerthat returns a player withlevelone higher and everything else unchanged. Use struct update syntax (..p).