liveBook · Manning

Struct

As explained in Rust in Action: Systems programming concepts and techniques

A struct is a Rust data structure that defines a composite value with named fields and their types.

A struct is Rust’s foundational compound data type: it combines named fields and their types into one value. A File can group a name with zero or more bytes, making the modeled file easier to handle as a whole. section 3.0 section 3.2

Listing 3.2 Defining an instance of struct to represent files
 #[derive(Debug)]                     #1
 struct File {
   name: String,
   data: Vec<u8>,                     #2
 }
 
 fn main() {
   let f1 = File {
     name: String::from("f1.txt"),    #3
     data: Vec::new(),                #4
   };
 
   let f1_name = &f1.name;            #5
   let f1_length = &f1.data.len();    #5
 
   println!("{:?}", f1);
   println!("{} is {} bytes long", f1_name, f1_length);
 }

This listing shows a File definition, literal construction with String and Vec values, borrowed field access, and debug output. section 3.2

A struct-based value supports several practical operations:

  • Define fields with associated types; reference fields require explicit lifetimes when those lifetimes cannot be elided. section 3.2
  • Create instances with literal syntax, then access fields directly or borrow their data with references. section 3.2
  • Add constructors and behavior in an impl block; new() provides a less verbose convention than repeated literals. section 3.3.1
  • Keep modeled data in memory without implying that the struct itself writes to persistent storage. section 3.2

Modeling and reading a file

A File with name: String and data: Vec<u8> can represent 2.txt and the bytes for “rust!”. Functions can open and close it, while read copies its contents into a supplied buffer and returns the byte count. section 3.2

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Defines fields, instances, borrowing, memory composition, and constructors, while deferring persistent storage and detailed pointer explanations.
Examples
Uses File values containing String names and Vec<u8> data, simulated open/read/close operations, and File::new constructors.
What it assumes
Assumes basic Rust values and types, while introducing composite modeling before detailed pointer and lifetime treatment.
What you can do after
Build it from scratch by defining structs, constructing instances, borrowing fields, and adding constructors or methods.
How it connects
Connects structs with compound data types, enums, methods, impl blocks, traits, borrowing, lifetimes, and filesystem modeling.

Also explained in

Compare how 14 books explain struct →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.