Skip to content

Group Related Fields in a Struct

The Course
•
26 min study

A study session has a topic and a number of minutes. You could keep two vectors, one of topics and one of durations, and trust that position 2 in one always matches position 2 in the other. That works until someone pushes to one vector and forgets the other, and then every later pair is wrong. A struct removes the problem by giving related data one name and one value.

The definition lists each field with its type. You build a value by supplying every field, and read a field with a dot, as in session.minutes. A Session can own its topic as a String. The struct owns its fields, so moving a Session moves its String along with it, and a function can borrow the whole session with &Session and read any field through that borrow.

Predict and run

Which fields does show use? Will main still be able to read the minutes?

Predict, then run Rust
struct Session {
    topic: String,
    minutes: u32,
}

fn show(session: &Session) {
    println!("{}: {} min", session.topic, session.minutes);
}

fn main() {
    let session = Session {
        topic: String::from("Structs"),
        minutes: 25,
    };
    show(&session);
    println!("Saved {} minutes", session.minutes);
}
Check your prediction
Text
Structs: 25 min
Saved 25 minutes

show received a reference, so it could read both fields without taking the session away. main still owns the value afterward. Add a second session with a different topic and duration, and call show with a reference to it. Then change the parameter to session: Session and the call to show(session): predict which line the compiler will now reject.

Build values in one place

Every field must be supplied when you build a struct. Leaving one out is a compile error, not a silent default:

Rust
let session = Session {
    topic: String::from("Structs"),
};

Rust reports error[E0063]: missing field minutes in initializer of Session. This is useful: when you later add a field to Session, the compiler points at every place that builds one.

When building sessions in several places, a small function keeps the rules together. If a variable has the same name as a field, you can write the name once, as minutes instead of minutes: minutes. This is called field init shorthand.

Build sessions with a function Rust
struct Session {
    topic: String,
    minutes: u32,
}

fn new_session(topic: &str, minutes: u32) -> Session {
    Session {
        topic: String::from(topic),
        minutes,
    }
}

fn main() {
    let sessions = vec![new_session("Vectors", 20), new_session("Structs", 30)];
    let mut total = 0;
    for session in &sessions {
        println!("{}: {} min", session.topic, session.minutes);
        total += session.minutes;
    }
    println!("Total: {total} min");
}
Text
Vectors: 20 min
Structs: 30 min
Total: 50 min

The function borrows a text slice and returns a Session that owns its own copy of the text. A vector of structs, Vec<Session>, keeps each topic and duration together, so they can never drift apart.

Change a field

Mutability belongs to the binding, not to individual fields. To change minutes, the whole session must be declared with let mut.

Extend a session Rust
struct Session {
    topic: String,
    minutes: u32,
}

fn main() {
    let mut session = Session {
        topic: String::from("Structs"),
        minutes: 25,
    };
    session.minutes += 10;
    session.topic.push_str(" review");
    println!("{}: {} min", session.topic, session.minutes);
}
Text
Structs review: 35 min

Without mut, the compiler stops at the first change with error[E0594]: cannot assign to session.minutes, as session is not declared as mutable.

Why println! cannot print a whole struct

println!("{session}") fails with error[E0277]: Session doesn't implement std::fmt::Display. Rust does not guess how your type should look to a reader, so print the fields you want. You will learn to describe a type's display yourself in a later course.

Practice

Exercise

Your turn

Define Book with an owned title and a u32 page count. Write a function that borrows a book and prints Rust Notes: 80 pages. Then print Still on the shelf: Rust Notes from main to show the book was not moved.

Your working space Rust
fn main() {
    // Create a Book, then pass a reference to it.
}
Hint 1: the idea

The book owns the text. The display function only needs a borrow.

Hint 2: a first step

Declare a struct with fields title: String and pages: u32, then write fn show(book: &Book).

Worked solution
Run the solution Rust
struct Book {
    title: String,
    pages: u32,
}

fn show(book: &Book) {
    println!("{}: {} pages", book.title, book.pages);
}

fn main() {
    let book = Book {
        title: String::from("Rust Notes"),
        pages: 80,
    };
    show(&book);
    println!("Still on the shelf: {}", book.title);
}
Text
Rust Notes: 80 pages
Still on the shelf: Rust Notes

The parameter type &Book says exactly what show needs: a look at the book, not ownership of it. That is why the last line can still read book.title. In the next lesson you will give a struct a field that can only hold one of a fixed set of values.

Was this article helpful?

Your response is saved on this device.