liveBook · Manning

Struct

As explained in Learn Rust in a Month of Lunches

A struct is a composite data type or structure that groups related fields or values into a single unit.

A `struct` creates a Rust type that groups related values. Think of a country with a population, capital, and leader: those properties belong together. Use an `enum` instead when you need to select one of several choices. section 4.1 section 4.1.1

Rust has three forms of struct:

  • A unit struct has no fields: `struct FileDirectory;` section 4.1.1
  • A tuple struct has values without field names. Access them by position, such as `my_color.1`. section 4.1.1
  • A named struct lists field names and types inside braces. This is the most common form. section 4.1.1
struct Country {
    population: u32,
    capital: String,
    leader_name: String
}
 
fn main() {
    let population = 500_000;
    let capital = String::from("Elista");
    let leader_name = String::from("Batu Khasikov");
 
    let kalmykia = Country {
        population,
        capital,
        leader_name,
    };
}

The `Country` declaration gives each field a name and type. Creating a `Country` requires a value for every field. When a variable already has the same name as its field, you can write `population` rather than `population: population`. section 4.1.1

Name struct types in `UpperCamelCase`; the compiler warns if you use lowercase instead. You can then give a struct behavior with an `impl` block. A method uses `self` in some form and is usually called with a dot. An associated function does not take `self` and is called with `::`; it can create a new value. To print a struct with `{:?}`, add `#[derive(Debug)]` above its declaration. section 4.1.1 section 4.1.5

A struct for JSON data

A `CurrentArticle` struct groups the `title`, `description`, and `extract` fields needed from a JSON response. Deriving `Deserialize` lets `serde_json::from_str()` convert the response into that struct. section 23.3.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through unit, tuple, and named forms, complete initialization, field shorthand, and methods without addressing memory layout.
Examples
Uses a country’s fields, positional color values, an animal with methods, and article data parsed from JSON.
What it assumes
Assumes familiarity with basic Rust variables, types, and tuples while defining each struct form as it appears.
What you can do after
Build it from scratch with struct declarations and complete initializers, then attach methods through an impl block.
How it connects
Connects structs to tuples, enums, impl blocks, methods, associated functions, and JSON deserialization.

Also explained in

Compare how 14 books explain struct →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.