What is a Struct?
Part of the Logic & Flow section of Coddy's Rust journey — lesson 20 of 66.
So far, you've worked with individual pieces of data - single numbers, strings, and collections like vectors. But what happens when you need to group related information together? For example, how would you represent a person with a name, age, and email address?
This is where structs come in. A struct is Rust's way of creating custom data types by bundling related values into a single, organized unit.
Each piece of data inside a struct is called a field. Fields have names and types, making it clear what each piece of information represents.
Example of a struct with different field types:
struct Person {
name: String,
age: u32,
active: bool,
}Here a Person struct have a name field of type String, an age field of type u32, and an active field of type bool.
Cheat sheet
A struct is a custom data type that groups related values together. Each value inside a struct is called a field, which has a name and a type.
Defining a struct:
struct Person {
name: String,
age: u32,
active: bool,
}In this example, Person is a struct with three fields: name (String), age (u32), and active (bool).
Try it yourself
This lesson doesn't include a code challenge.
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