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













