capypad
0 day streak
rust / beginner
Snippet

Creating Struct Instances

Structs group related data. The 'impl' block attaches methods to a struct. 'Self' refers to the struct type, 'self' refers to the instance. The 'new' constructor pattern is conventional. Instance fields are accessed using dot notation.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct Person {
name: String,
age: u32,
active: bool,
}
 
impl Person {
fn new(name: &str, age: u32) -> Self {
Self { name: String::from(name), age, active: true }
}
fn introduce(&self) {
println!("Hi, I'm {} and I'm {} years old", self.name, self.age);
}
}
 
fn main() {
let alice = Person::new("Alice", 30);
let bob = Person { name: String::from("Bob"), age: 25, active: true };
alice.introduce();
println!("{} is active: {}", bob.name, bob.active);
}
Breakdown
1
struct Person { ... }
Struct definition with three fields of different types
2
impl Person { fn new(...) -> Self { ... } }
Associated function as constructor returning Self
3
let alice = Person::new("Alice", 30);
Call constructor using :: syntax
4
alice.introduce();
Method call uses dot notation, self is borrowed