🎓 A1Learner
🔍

Rust Nested Structs

A nested struct is a struct held in a field of another struct. A Rectangle can hold two Points instead of four loose numbers.

A struct inside a struct

A field can be any type — even another struct. Build the inner values right where you need them, and read deep inside with chained dots: rect.top_left.x is the x of the top_left of rect:

struct Point { x: i32, y: i32 }
struct Rectangle { top_left: Point, bottom_right: Point }
let rect = Rectangle { top_left: Point { x: 1, y: 4 }, bottom_right: Point { x: 5, y: 1 } };
println!("corner = ({}, {})", rect.top_left.x, rect.top_left.y);

Or build the inner struct first

Make the Point on its own line, then move it in:

let corner = Point { x: 1, y: 4 };
let rect = Rectangle { top_left: corner, bottom_right: Point { x: 5, y: 1 } };
println!("corner x = {}", rect.top_left.x);

Change a deep field

With mut on the whole value, one number deep inside can change:

let mut rect = Rectangle { top_left: Point { x: 1, y: 4 }, bottom_right: Point { x: 5, y: 1 } };
rect.top_left.x = 2;
println!("new corner = ({}, {})", rect.top_left.x, rect.top_left.y);

Reuse the small struct anywhere

The same Point can serve inside many bigger structs — each small struct stays simple:

struct Triangle { a: Point, b: Point, c: Point }
let tri = Triangle { a: Point { x: 0, y: 0 }, b: Point { x: 4, y: 0 }, c: Point { x: 0, y: 3 } };
println!("tip = ({}, {})", tri.c.x, tri.c.y);

Example

struct Point { x: i32, y: i32 }
struct Rectangle { top_left: Point, bottom_right: Point }
fn main() {
    let rect = Rectangle {
        top_left: Point { x: 1, y: 4 },
        bottom_right: Point { x: 5, y: 1 },
    };
    let width = rect.bottom_right.x - rect.top_left.x;
    let height = rect.top_left.y - rect.bottom_right.y;
    println!("corner = ({}, {})", rect.top_left.x, rect.top_left.y);
    println!("width = {} height = {} area = {}", width, height, width * height);
}

Key points

  • Each Point keeps its own name and shape.
  • The same small struct can be reused in many bigger structs.

In this example, Point is a small struct with x and y. Rectangle is a bigger struct whose two fields are Points: top_left and bottom_right. main builds one Rectangle with two Points inside it, written in place. width is the gap between the two x values: 5 - 1 = 4. height is the gap between the two y values: 4 - 1 = 3. The corner line reads deep inside with chained dots: rect.top_left.x is 1 and rect.top_left.y is 4. The last line prints width = 4 height = 3 area = 12.

Note

Small structs become the building blocks of bigger ones.

Each small struct stays simple.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

How do you read the y of the bottom_right point of rect?