WeCodeAcademy

Rust Structs and Methods

ExampleRust
struct Person {
    name: String,
    age: u32,
}

impl Person {
    fn new(name: &str, age: u32) -> Person {
        Person { name: name.to_string(), age }
    }

    fn describe(&self) -> String {
        format!("{} is {}", self.name, self.age)
    }

    fn birthday(&mut self) {
        self.age += 1;
    }
}

fn main() {
    let mut p = Person::new("Ada", 36);
    p.birthday();
    println!("{}", p.describe());
}
Output
Ada is 37

Methods live in an impl block. &self reads the value, &mut self can change it.

Quick check

Which receiver lets a method modify the struct?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.