Structs Overview
Part of the Logic & Flow section of Coddy's Rust journey — lesson 21 of 66.
Now that you understand what structs are, let's learn how to actually create and use them. This involves two steps: first defining the struct's structure, then creating instances of it.
To define a struct, you use the struct keyword followed by the struct's name and its fields inside curly braces. Each field has a name and a type:
struct User {
username: String,
active: bool,
}This creates a blueprint for a User struct with two fields: username of type String and active of type bool.
Naming convention: Struct names in Rust should use PascalCase (also called UpperCamelCase), meaning each word starts with a capital letter — for example, User, ProductItem, or ShoppingCart. Rust will warn you if you don't follow this convention.
Once you've defined a struct, you can create instances of it by specifying values for each field:
let user1 = User {
username: String::from("alice"),
active: true,
};Notice that you provide the struct name followed by curly braces containing each field name, a colon, and its value. The order of fields doesn't have to match the definition order.
To access the fields of a struct instance, use dot notation — write the instance name followed by a dot and the field name:
println!("Username: {}", user1.username);
println!("Active: {}", user1.active);Here, user1.username accesses the username field of user1, and user1.active accesses the active field. You can use these field values anywhere you would use a regular variable.
Challenge
EasyYou will receive three inputs: a product name, a price (as a decimal number), and a stock quantity (as an integer). Define a Product struct with three fields: name of type String, price of type f64, and stock of type i32. Then create an instance of this struct using the input values and print the product information.
Requirements:
- Define a
Productstruct with fields:name: String,price: f64, andstock: i32 - Read the first input as the product name
- Read the second input and convert it to
f64for the price - Read the third input and convert it to
i32for the stock quantity - Create an instance of the
Productstruct with these values - Print the product information in the exact format shown below
Input:
- First line: Product name (e.g.,
Laptop) - Second line: Price as a decimal number (e.g.,
999.99) - Third line: Stock quantity as an integer (e.g.,
15)
Output:
- First line:
Product: [name] - Second line:
Price: $[price] - Third line:
Stock: [quantity]
Try it yourself
use std::io;
// TODO: Define your Product struct here
fn main() {
// Read product name
let mut name = String::new();
io::stdin().read_line(&mut name).expect("Failed to read line");
let name = name.trim().to_string();
// Read price
let mut price_input = String::new();
io::stdin().read_line(&mut price_input).expect("Failed to read line");
let price: f64 = price_input.trim().parse().expect("Failed to parse price");
// Read stock quantity
let mut stock_input = String::new();
io::stdin().read_line(&mut stock_input).expect("Failed to read line");
let stock: i32 = stock_input.trim().parse().expect("Failed to parse stock");
// TODO: Create an instance of Product struct using the input values
// TODO: Print the product information in the required format
}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