Skip to the workspace
Pebellslearn by building
Types and Error Handling  ›  Lesson

Structs and Impl Blocks

Structs 12 minA struct names a group of fields as one new type, and an impl block attaches constructors and methods to it.

rust / Structs and Impl Blocks

Explore each scene at your own pace.

01 · The rule

The rule

Structs and Impl Blocks

A struct names a group of fields as one new type, and an impl block attaches constructors and methods to it.

Group related fields and attach behavior through an impl block.

So far the library's data has been loose variables: a title here, a page count there. Real programs group related facts into one named thing. In Rust that thing is a struct, and the error-handling tools later in this section all sit on top of types like it.

The rule

A struct groups named fields; an impl block gives it behaviour.

Define a struct with typed fields:

#[derive(Debug)]
struct Book {
    title: String,
    pages: u32,
    on_loan: bool,
}

#[derive(Debug)] lets you print it with {:?}.

Create one by naming every field. If a variable has the same name as a field, write it once (field init shorthand):

let pages = 380;
let book = Book { title: String::from("Iron Tides"), pages, on_loan: false };
println!("{}", book.pages);

The whole value is mutable or not; you cannot mark one field mut. Use let mut book to change book.on_loan.

Attach behaviour with impl. Inside, Self is a short name for the type:

impl Book {
    fn new(title: &str, pages: u32) -> Self {
        Self { title: title.to_string(), pages, on_loan: false }
    }
    fn is_available(&self) -> bool {
        !self.on_loan
    }
    fn lend(&mut self) {
        self.on_loan = true;
    }
}

let mut book = Book::new("Iron Tides", 380);
book.lend();
println!("{}", book.is_available()); // false

A type may have several impl blocks, and new is only a naming habit, not a keyword.

Two other shapes exist: tuple structs with unnamed fields, such as struct CardNumber(u32);, useful for giving a plain number its own type; and unit structs with no fields.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.