Beginner Fundamentals
Structs
A struct groups related data under one named type. It is the main way to model custom data in Rust.
Defining a struct
struct User {
name: String,
age: u32,
active: bool,
}
Creating an instance
Fill every field by name. Access fields with a dot.
fn main() {
let user = User {
name: String::from("Alice"),
age: 30,
active: true,
};
println!("{} is {}", user.name, user.age);
}
To change fields, the instance must be declared with mut.
Methods with impl
An impl block adds methods to a struct. Methods take &self to borrow the instance.
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
// Associated function (no self): acts like a constructor
fn square(size: u32) -> Rectangle {
Rectangle { width: size, height: size }
}
}
fn main() {
let rect = Rectangle { width: 4, height: 5 };
println!("Area: {}", rect.area()); // 20
let sq = Rectangle::square(3);
println!("Area: {}", sq.area()); // 9
}
Associated functions are called with ::, while methods are called with ..