Structs & Methods in Rust
From the Rust cheat sheet ยท Structs & Enums ยท verified Jul 2026
Structs & Methods
Define structs and attach methods with impl blocks.
rust
#[derive(Debug)]
struct User {
name: String,
age: u32,
active: bool,
}
impl User {
// Associated function (constructor)
fn new(name: &str, age: u32) -> Self {
Self { name: name.to_string(), age, active: true }
}
// Method (takes &self)
fn is_adult(&self) -> bool {
self.age >= 18
}
}
let user = User::new("Alice", 30);
println!("{:?}", user);๐ก &self borrows, &mut self borrows mutably, self takes ownership โ pick the least powerful one
โก Self is an alias for the struct type inside impl blocks โ use it in constructors
๐ Struct update syntax (..other) moves fields from other โ clone first if you still need it
๐ข Convention: use new() as the constructor name, like User::new()
structsmethodsimpl