C.W.K.
Stream
Lesson 03 of 05 · published

Defining Structs

~11 min · types, structs, data-modeling

Level 0Rust Curious
0 XP0/80 lessons0/19 achievements
0/100 XP to next level100 XP to go0% complete

A struct is how you name and group related data into your own type. Rust gives you three shapes, and you'll reach for the first one most.

Named-field structs

The workhorse: fields with names and types. You create an instance by naming each field, and access fields with dot notation. Because the fields are named, the code reads itself — user.email beats user.2 every time.

Tuple structs and unit structs

A tuple struct has typed fields without names — handy for a thin wrapper like struct Meters(f64) that gives a bare number a distinct type. A unit struct has no fields at all — useful as a marker or when you'll implement a trait on it but store no data. Both are niche; named-field structs carry the day.

Field init shorthand and struct update. When a variable has the same name as a field, write just email instead of email: email. And ..other at the end of a literal fills remaining fields from another instance — great for 'same as that one, but change this.'

Structs are the heart of modeling

Where ownership tells you how data moves, structs tell you what the data is. A well-named struct with well-chosen field types makes invalid states hard to represent — the first half of Rust's 'make illegal states unrepresentable' philosophy. (The other half is enums, the very next track.)

Code

Named-field, tuple struct, shorthand, and update syntax·rust
#[derive(Debug)]
struct User {
    name: String,
    email: String,
    active: bool,
}

struct Meters(f64); // tuple struct: a distinct type around an f64

fn main() {
    let name = String::from("Ferris");
    let u = User {
        name,                      // field init shorthand (name: name)
        email: String::from("f@rust.org"),
        active: true,
    };
    // struct update: same as u, but inactive
    let u2 = User { active: false, ..u };
    let dist = Meters(42.0);
    println!("{:?} active={} dist={}", u2.name, u2.active, dist.0);
}

External links

Exercise

Define a User struct with at least three fields. Build one instance with field init shorthand, then build a second using struct update syntax (..first) that changes just one field. Derive Debug and print both. What does the update syntax do with the String fields it copies from the first instance?
Hint
Struct update *moves* non-Copy fields like String out of the source. After ..u, the moved fields of u are no longer usable — the same ownership rule you learned, now inside struct literals.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue
💛 by Ttoriwarm

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.