← 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.
Syntax
rust
struct Name {
    field1: Type1,
    field2: Type2,
}

let value = Name { field1: v1, field2: v2 };
value.field1

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
// Define a struct `User` to group related fields together
struct User {
    name: String,
    age: u32,
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `user`, set to `User { name: String::from("Ada"), age: 30 }`
    let user = User { name: String::from("Ada"), age: 30 };
    // Print "{} is {} years old" to the console, substituting in `user.name, user.age` (with a trailing newline)
    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
// Define a struct `Point` to group related fields together
struct Point {
    x: f64,
    y: f64,
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `origin`, set to `Point { x: 0.0, y: 0.0 }`
    let origin = Point { x: 0.0, y: 0.0 };
    // Print "({}, {})" to the console, substituting in `origin.x, origin.y` (with a trailing newline)
    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
// Define a struct `Counter` to group related fields together
struct Counter {
    value: i32,
}

// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `counter`, initialized to `Counter { value: 0 }`
    let mut counter = Counter { value: 0 };
    counter.value += 1;
    counter.value += 1;
    // Print "Counter is at {}" to the console, substituting in `counter.value` (with a trailing newline)
    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
// Define a struct `Point3D` to group related fields together
struct Point3D {
    x: i32,
    y: i32,
    z: i32,
}

// Define the function `make_point` taking `x`, `y`, `z` and returning a `Point3D`
fn make_point(x: i32, y: i32, z: i32) -> Point3D {
    Point3D { x, y, z }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `p`, set to `make_point(1, 2, 3)`
    let p = make_point(1, 2, 3);
    // Print "({}, {}, {})" to the console, substituting in `p.x, p.y, p.z` (with a trailing newline)
    println!("({}, {}, {})", p.x, p.y, p.z);
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.