1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-04-25 08:53:01 +02:00
comprehensive-rust/src/methods.md
2022-12-21 16:38:28 +01:00

420 B

Methods

Rust allows you to associate functions with your new types. You do this with an impl block:

#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
}

impl Person {
    fn say_hello(&self) {
        println!("Hello, my name is {}", self.name);
    }
}

fn main() {
    let peter = Person {
        name: String::from("Peter"),
        age: 27,
    };
    peter.say_hello();
}