liveBook · Manning

Struct

As explained in Refactoring to Rust

A struct is a Rust composite type that groups named fields into a single logical value and can have associated functionality.

A Rust struct groups named fields into one logical value. It is similar to a class, but does not support inheritance. Start with an artwork that has one field: `name: String`. A value supplies that field when it is created; `to_string()` converts the name’s string literal into a `String`. section 2.1

Listing 2.2 Struct representing an artwork
struct Artwork {
  name: String,
}

fn main() {
  let art1 = Artwork {
    name: "Boy with Apple".to_string()
  };
}

The `Artwork` declaration names the field and its type; the value created in `main` supplies the field’s value. section 2.1

Passing an `Artwork` to `admire_art(art: Artwork)` moves that value into the function. Trying to pass the same variable again produces a “use of moved value” error. The grouped fields make a convenient function argument, but ownership still matters. section 2.1

The same pattern scales to external data:

  • For JSON with a string `name` and numeric `value`, define `struct Data { name: String, value: i32 }`. Derive `serde::Deserialize`, then give the parsed result the type `Data` when calling `serde_json::from_str`. section 6.3
  • For an XML search feed, define related `Feed`, `Entry`, and `Author` structs. Fields include `Vec<Entry>` and `Vec<Author>`; the fetched XML is parsed into a `Feed`. section 9.3.1

When the data does not match

If JSON supplies a string for `name` but `Data` declares `name: i32`, deserialization reports a type error. In the shown code, calling `unwrap()` on that error causes a panic. A struct’s field types therefore describe what the parser expects, not what arbitrary input will contain. section 6.3

How Refactoring to Rust covers it

How deep it goes
Defines named fields and initialization, then demonstrates moves and derived deserialization; does not develop struct methods.
Examples
Uses an artwork value, a JSON name-and-number record, and nested XML search results.
What it assumes
Introduces structs from a small Cargo project while explaining `let` initialization and string-literal conversion.
What you can do after
Build it from scratch as a named-field value, and apply it via Serde to parse JSON or XML.
How it connects
Connects structs to ownership, type annotations, Serde deserialization, and nested collections.

Also explained in

Compare how 14 books explain struct →

Related concepts

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