Struct Basics
In this page:
Defining a Struct
The struct keyword defines a new custom type with named fields, each with its own type. This groups related data together under one meaningful name instead of using separate loose variables.
Example: Defining a Struct
struct User {
name: String,
age: u32,
}
fn main() {
let user = User { name: String::from("Ada"), age: 30 };
println!("{} is {} years old", user.name, user.age);
}
Login to try C/C++/Java/PHP code in the editor
Creating Struct Instances
You create an instance of a struct with a struct literal: the type name followed by curly braces listing a value for every field. All fields must be provided.
Example: Creating Struct Instances
struct Point {
x: f64,
y: f64,
}
fn main() {
let origin = Point { x: 0.0, y: 0.0 };
println!("({}, {})", origin.x, origin.y);
}
Login to try C/C++/Java/PHP code in the editor
Accessing and Modifying Fields
Fields are read using dot notation. If the struct instance is bound with mut, its fields can also be reassigned individually after creation.
Example: Accessing and Modifying Fields
struct Counter {
value: i32,
}
fn main() {
let mut counter = Counter { value: 0 };
counter.value += 1;
counter.value += 1;
println!("Counter is at {}", counter.value);
}
Login to try C/C++/Java/PHP code in the editor
Field Init Shorthand
When a variable's name matches a struct field's name, you can omit repeating the name, writing just the variable instead of field: field.
Example: Field Init Shorthand
struct Point3D {
x: i32,
y: i32,
z: i32,
}
fn make_point(x: i32, y: i32, z: i32) -> Point3D {
Point3D { x, y, z }
}
fn main() {
let p = make_point(1, 2, 3);
println!("({}, {}, {})", p.x, p.y, p.z);
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting a field when constructing a struct literal, which the compiler rejects since every field is required.
- Trying to make just one field of a struct instance mutable -- mutability applies to the whole variable binding, not per field.
- Confusing struct field access
instance.fieldwith function calls, forgetting there is no parentheses for plain field access.
- A struct groups related named fields together under one custom type, defined with the
structkeyword. - Struct instances are created with a struct literal listing every field's value.
- Fields are accessed with dot notation, e.g.
instance.field. - Marking an instance variable
mutallows changing any of its fields afterward.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: