1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-06 17:46:16 +02:00

31 lines
682 B
Markdown
Raw Normal View History

2022-12-21 16:36:30 +01:00
# Methods
Rust has methods, they are simply functions that are associated with a particular type. The
first argument of a method is an instance of the type it is associated with:
```rust,editable
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn inc_width(&mut self, delta: u32) {
self.width += delta;
}
}
fn main() {
let mut rect = Rectangle { width: 10, height: 5 };
println!("old area: {}", rect.area());
rect.inc_width(5);
println!("new area: {}", rect.area());
}
```
* We will look much more at methods in today's exercise and in tomorrow's class.