Accessing Struct Fields
Part of the Logic & Flow section of Coddy's Rust journey — lesson 22 of 66.
Once you've created a struct instance, you need a way to retrieve the values stored inside it. Rust uses dot notation to access individual fields within a struct.
The syntax is straightforward: you write the struct instance name, followed by a dot, then the field name you want to access:
let product = Product {
name: String::from("Laptop"),
price: 999,
};
println!("Product: {}", product.name);
println!("Price: ${}", product.price);This dot notation works just like accessing properties in other programming languages. You can use the accessed values in expressions, assign them to variables, or pass them to functions - they behave exactly like any other value of that type.
Challenge
EasyYou will receive three inputs: a car model name, the car's year (as an integer), and its mileage (as an integer). Define a Car struct with three fields: model of type String, year of type i32, and mileage of type i32. Create an instance of this struct using the input values, then access and print each field.
Requirements:
- Define a
Carstruct with fields:model: String,year: i32, andmileage: i32 - Read the first input as the car model
- Read the second input and convert it to
i32for the year - Read the third input and convert it to
i32for the mileage - Create an instance of the
Carstruct with these values - Use dot notation to access each field and print the car information in the exact format shown below
Input:
- First line: Car model (e.g.,
Tesla Model 3) - Second line: Year as an integer (e.g.,
2022) - Third line: Mileage as an integer (e.g.,
15000)
Output:
- First line:
Car: [model] - Second line:
Year: [year] - Third line:
Mileage: [mileage] km
Cheat sheet
To access fields within a struct instance, use dot notation:
let product = Product {
name: String::from("Laptop"),
price: 999,
};
println!("Product: {}", product.name);
println!("Price: ${}", product.price);The syntax is: instance_name.field_name. Accessed values can be used in expressions, assigned to variables, or passed to functions.
Try it yourself
use std::io;
// TODO: Define the Car struct here with fields: model, year, and mileage
fn main() {
// Read the car model
let mut model = String::new();
io::stdin().read_line(&mut model).expect("Failed to read line");
let model = model.trim().to_string();
// Read the year
let mut year_input = String::new();
io::stdin().read_line(&mut year_input).expect("Failed to read line");
let year: i32 = year_input.trim().parse().expect("Invalid year");
// Read the mileage
let mut mileage_input = String::new();
io::stdin().read_line(&mut mileage_input).expect("Failed to read line");
let mileage: i32 = mileage_input.trim().parse().expect("Invalid mileage");
// TODO: Create an instance of the Car struct using the input values
// TODO: Access and print each field in the required format
// Car: [model]
// Year: [year]
// Mileage: [mileage] km
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together