mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-04-26 09:12:58 +02:00
28 lines
420 B
Markdown
28 lines
420 B
Markdown
# Methods
|
|
|
|
Rust allows you to associate functions with your new types. You do this with an
|
|
`impl` block:
|
|
|
|
```rust,editable
|
|
#[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();
|
|
}
|
|
```
|
|
|