rust / beginner
Snippet
Implementing Methods with impl
The impl block lets you associate functions and methods with a struct. Methods are similar to functions but always have self as their first parameter. The new function acts as a constructor, returning a new instance of Rectangle.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct Rectangle {width: u32,height: u32,}impl Rectangle {fn area(&self) -> u32 {self.width * self.height}fn new(width: u32, height: u32) -> Self {Rectangle { width, height }}}let rect = Rectangle::new(30, 50);println!("Area: {}", rect.area());
Breakdown
1
impl Rectangle {
Starts an impl block for the Rectangle struct
2
fn area(&self) -> u32 {
Method that takes an immutable reference to self
3
self.width * self.height
Accesses fields of the struct instance
4
fn new(width: u32, height: u32) -> Self {
Associated function acting as a constructor
5
Rectangle { width, height }
Shorthand syntax to create the struct instance
6
Rectangle::new(30, 50)
Calls the constructor via the type name