rust / beginner
Snippet
Method Syntax with impl Blocks
The impl block lets you associate methods with a struct. Methods are similar to functions but are defined within an impl block and always have self as their first parameter. self refers to the instance the method is called on. Associated functions like new() are often used as constructors.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct Rectangle {width: u32,height: u32,}impl Rectangle {fn area(&self) -> u32 {self.width * self.height}fn new(width: u32, height: u32) -> Rectangle {Rectangle { width, height }}fn can_hold(&self, other: &Rectangle) -> bool {self.width > other.width && self.height > other.height}}fn main() {let rect = Rectangle::new(30, 50);println!("Area: {}", rect.area());}
Breakdown
1
impl Rectangle { ... }
Block that groups methods associated with Rectangle
2
fn area(&self) -> u32
Method taking immutable reference to self
3
Rectangle::new(30, 50)
Calls associated function using struct name