capypad
0 day streak
rust / beginner
Snippet

Defining and Using Structs

Structs are custom data types that group related fields together. The impl block allows us to define methods for the struct. The new function is a common convention for constructor-like behavior, returning Self (the struct type itself).

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 }
}
}
 
fn main() {
let rect = Rectangle::new(30, 50);
println!("Area: {}", rect.area());
}
Breakdown
1
struct Rectangle {
Declares a struct named Rectangle
2
width: u32,
First field of type unsigned 32-bit integer
3
height: u32,
Second field of type unsigned 32-bit integer
4
impl Rectangle {
Implementation block for Rectangle methods
5
fn area(&self) -> u32 {
Method taking immutable reference to self
6
Self { width, height }
Shorthand for Rectangle { width: width, height: height }