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 of Book { title: title, pages: pages }.
  • Struct update syntax: Book { pages: 400, ..old } builds a new value, taking every field you did not list from old. Fields that are not Copy (like String) are moved out of old.

Your task

The tests build and read your struct, so it and its fields must be pub.

  1. Define pub struct Player with public fields name: String, level: u32 and health: i32.
  2. Write pub fn new_player(name: String, level: u32) -> Player that starts with health of 100. Use field init shorthand for name and level.
  3. Write pub fn level_up(p: Player) -> Player that returns a player with level one higher and everything else unchanged. Use struct update syntax (..p).

Next lesson →

Sign in to run your code. It's free.