Structs as Function Parameters
Part of the Logic & Flow section of Coddy's Rust journey — lesson 24 of 66.
Now that you know how to create and modify structs, let's explore how to use them with functions. Just like any other data type in Rust, you can pass struct instances to functions and return them from functions.
To pass a struct to a function, you simply include it as a parameter in the function definition:
fn calculate_area(rect: Rectangle) -> i32 {
rect.width * rect.height
}This function takes a Rectangle struct as a parameter and returns an i32. Inside the function, you can access the struct's fields using dot notation, just like you would anywhere else.
You can also return structs from functions by specifying the struct type as the return type:
fn create_square(size: i32) -> Rectangle {
Rectangle {
width: size,
height: size,
}
}Using structs with functions makes your code more organized and meaningful. Instead of passing multiple individual parameters, you can group related data together and pass it as a single, well-defined unit.
Challenge
EasyYou will receive four inputs: a rectangle's width (as an integer), a rectangle's height (as an integer), a square's side length (as an integer), and a choice number (1 or 2). Define a Rectangle struct with two fields: width: i32 and height: i32. Create two functions: one that takes a Rectangle and calculates its area, and another that takes a side length and returns a Rectangle representing a square. Based on the choice input, calculate and print the appropriate area.
Requirements:
- Define a
Rectanglestruct with fields:width: i32andheight: i32 - Create a function
calculate_areathat takes aRectangleas a parameter and returns ani32(the area) - Create a function
create_squarethat takes ani32(side length) as a parameter and returns aRectanglewith equal width and height - Read the first input and convert it to
i32for the rectangle's width - Read the second input and convert it to
i32for the rectangle's height - Create a
Rectangleinstance with these dimensions - Read the third input and convert it to
i32for the square's side length - Read the fourth input and convert it to
i32for the choice (1 or 2) - If choice is 1: calculate and print the area of the rectangle
- If choice is 2: create a square using
create_square, then calculate and print its area
Input:
- First line: Rectangle width as an integer (e.g.,
8) - Second line: Rectangle height as an integer (e.g.,
5) - Third line: Square side length as an integer (e.g.,
6) - Fourth line: Choice as an integer, either 1 or 2 (e.g.,
1)
Output:
- If choice is 1:
Rectangle area: [area] - If choice is 2:
Square area: [area]
Cheat sheet
Structs can be passed to functions as parameters and returned from functions.
To pass a struct to a function, include it as a parameter:
fn calculate_area(rect: Rectangle) -> i32 {
rect.width * rect.height
}To return a struct from a function, specify the struct type as the return type:
fn create_square(size: i32) -> Rectangle {
Rectangle {
width: size,
height: size,
}
}Inside functions, access struct fields using dot notation. Using structs with functions allows you to group related data together instead of passing multiple individual parameters.
Try it yourself
use std::io;
// TODO: Define the Rectangle struct here
// TODO: Define the calculate_area function here
// TODO: Define the create_square function here
fn main() {
// Read rectangle width
let mut width_input = String::new();
io::stdin().read_line(&mut width_input).expect("Failed to read line");
let width: i32 = width_input.trim().parse().expect("Invalid input");
// Read rectangle height
let mut height_input = String::new();
io::stdin().read_line(&mut height_input).expect("Failed to read line");
let height: i32 = height_input.trim().parse().expect("Invalid input");
// Read square side length
let mut side_input = String::new();
io::stdin().read_line(&mut side_input).expect("Failed to read line");
let side: i32 = side_input.trim().parse().expect("Invalid input");
// Read choice
let mut choice_input = String::new();
io::stdin().read_line(&mut choice_input).expect("Failed to read line");
let choice: i32 = choice_input.trim().parse().expect("Invalid input");
// TODO: Write your code below
// Create a Rectangle instance, check the choice, and calculate the appropriate area
// Output the result based on choice
// Use: println!("Rectangle area: {}", area); or println!("Square area: {}", area);
}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