Rust Structs
A struct (short for structure) lets you create your own data type by grouping related values under named fields. Where a tuple says "a string, a number and a bool", a struct says "a name, an age and an active flag" — much easier to read and maintain.
Defining and creating a struct
Define the struct once with struct, listing each field and its type. Then create instances of it by filling in every field.
struct Player {
name: String,
level: u32,
health: f64,
}
fn main() {
let hero = Player {
name: String::from("Aria"),
level: 7,
health: 92.5,
};
println!("{} is level {} with {} HP", hero.name, hero.level, hero.health);
}Aria is level 7 with 92.5 HP
Fields are read with dot notation: hero.name. Struct names use UpperCamelCase; field names use snake_case.
Changing fields
To change a field, the whole instance must be declared mut. Rust does not allow marking only some fields as mutable.
struct Counter {
label: String,
count: u32,
}
fn main() {
let mut clicks = Counter {
label: String::from("Button A"),
count: 0,
};
clicks.count += 1;
clicks.count += 1;
clicks.label.push_str(" (main)");
println!("{}: {} clicks", clicks.label, clicks.count);
}Button A (main): 2 clicks
Shorthand and update syntax
Two shortcuts save typing:
- Field init shorthand: if a variable has the same name as a field, write just
nameinstead ofname: name. - Struct update syntax:
..othercopies the remaining fields from another instance.
#[derive(Debug)]
struct Config {
width: u32,
height: u32,
fullscreen: bool,
}
fn make_config(width: u32, height: u32) -> Config {
Config { width, height, fullscreen: false } // shorthand
}
fn main() {
let base = make_config(800, 600);
let big = Config { width: 1920, height: 1080, ..base };
println!("{:?}", base);
println!("{:#?}", big);
}Config { width: 800, height: 600, fullscreen: false }
Config {
width: 1920,
height: 1080,
fullscreen: false,
}
#[derive(Debug)] asks the compiler to generate printing code so you can use {:?} (one line) or {:#?} (pretty, multi-line).
Methods with impl
You attach functions to a struct in an impl block. A function whose first parameter is self is a method, called with value.method().
| First parameter | Meaning |
|---|---|
&self |
borrow the instance to read it |
&mut self |
borrow the instance to change it |
self |
take ownership (the instance is consumed) |
| (none) | an associated function, called as Type::name() — often a constructor called new |
struct Rectangle {
width: f64,
height: f64,
}
impl Rectangle {
fn new(width: f64, height: f64) -> Rectangle {
Rectangle { width, height }
}
fn square(size: f64) -> Self {
Self { width: size, height: size }
}
fn area(&self) -> f64 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
fn scale(&mut self, factor: f64) {
self.width *= factor;
self.height *= factor;
}
}
fn main() {
let mut door = Rectangle::new(2.0, 4.5);
let tile = Rectangle::square(1.5);
println!("Door area: {}", door.area());
println!("Tile area: {}", tile.area());
println!("Door can hold tile? {}", door.can_hold(&tile));
door.scale(2.0);
println!("Scaled door: {} x {}", door.width, door.height);
}Door area: 9
Tile area: 2.25
Door can hold tile? true
Scaled door: 4 x 9
Inside an impl block, Self is a shorthand for the type being implemented — here Rectangle.
Note: Floats like
9.0are printed as9by{}. Use{:.1}if you want a fixed number of decimals.
Tuple structs and unit structs
Sometimes you want a new named type but field names would add nothing. A tuple struct has unnamed fields accessed with .0, .1. A unit struct has no fields at all.
struct Celsius(f64);
struct Fahrenheit(f64);
struct Marker;
fn to_fahrenheit(c: Celsius) -> Fahrenheit {
Fahrenheit(c.0 * 9.0 / 5.0 + 32.0)
}
fn main() {
let boiling = Celsius(100.0);
let f = to_fahrenheit(boiling);
println!("Boiling point: {}°F", f.0);
let _m = Marker; // useful later with traits
}Boiling point: 212°F
Because Celsius and Fahrenheit are different types, the compiler stops you from passing a Fahrenheit value where Celsius is expected — even though both just wrap an f64.
Structs and ownership
A struct owns its fields. Using String fields (rather than &str) means each instance owns its own text, which is the simplest choice for beginners. When a struct goes out of scope, all its fields are dropped with it.
Test yourself
What must be true to change p.age on a struct instance p?
- The field must be marked
mut - The instance must be declared with
let mut - The struct must derive Debug
- Nothing, fields are always mutable
Which method signature lets a method modify the instance it is called on?
- fn grow(self)
- fn grow(&self)
- fn grow(&mut self)
- fn grow()
How is an associated function like Rectangle::new different from a method?
- It has no
selfparameter and is called withType::name() - It cannot return a value
- It must be marked
pub - It is only available in tests