← Back to Rust Course | Chapter 7: Structs | Lesson 1 of 7

Struct Basics

A struct is a custom box you design yourself, with named compartments for holding different pieces of related data together.

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

markup
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);
}

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

markup
struct Point {
    x: f64,
    y: f64,
}

fn main() {
    let origin = Point { x: 0.0, y: 0.0 };
    println!("({}, {})", origin.x, origin.y);
}

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

markup
struct Counter {
    value: i32,
}

fn main() {
    let mut counter = Counter { value: 0 };
    counter.value += 1;
    counter.value += 1;
    println!("Counter is at {}", counter.value);
}

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

markup
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);
}
Common Mistakes
  1. Forgetting a field when constructing a struct literal, which the compiler rejects since every field is required.
  2. Trying to make just one field of a struct instance mutable -- mutability applies to the whole variable binding, not per field.
  3. Confusing struct field access instance.field with function calls, forgetting there is no parentheses for plain field access.
Chapter Summary
  • A struct groups related named fields together under one custom type, defined with the struct keyword.
  • 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 mut allows changing any of its fields afterward.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.