summaryrefslogtreecommitdiff
path: root/Rust struct associated functions.md
blob: 4c5e660eb3b345e59747952af45b51b99eddeb37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Associated functions are an umbrella term for all `fn` declared in an `impl` block.
A method is just an associated `fn` with `Self` as its first argument but it's not mandatory, for ie constructors or what in PHP would be a static class function.

```rust
struct Rectangle {
  width: u32,
  height: u32,
}

impl Rectangle {
  fn area(&self) -> u32 {
    self.width * self.height
  }

  fn square(size: u32) -> Rectangle {
    Rectangle {
      width: size,
      height: size,
    }
  }
}
```