Recap - Safe Division Function
Part of the Logic & Flow section of Coddy's Rust journey — lesson 48 of 66.
Challenge
EasyYou will receive two inputs. The first input is a number representing the dividend, and the second input is a number representing the divisor. Create a function safe_divide that takes two f64 parameters and returns a Result<f64, &'static str>. The function should return Err("Cannot divide by zero") when the divisor is zero, and Ok with the division result otherwise. Use a match expression to handle the result and print the appropriate output.
Requirements:
- Read the first input (dividend) and trim whitespace
- Parse the first input to
f64 - Read the second input (divisor) and trim whitespace
- Parse the second input to
f64 - Create a function
safe_dividethat takes twof64parameters and returnsResult<f64, &'static str> - Inside the function, check if the divisor is
0.0:- If yes, return
Err("Cannot divide by zero") - If no, return
Ok(dividend / divisor)
- If yes, return
- Call the function with the two parsed numbers
- Use a
matchexpression to handle theResult - In the
Ok(value)arm, print:Division result: [value] - In the
Err(error)arm, print:Error: [error]
Input:
- First line: A number representing the dividend (e.g.,
20.0) - Second line: A number representing the divisor (e.g.,
4.0)
Output:
- If division is successful:
Division result: [result] - If division by zero:
Error: Cannot divide by zero
Try it yourself
use std::io;
// TODO: Create the safe_divide function here
// fn safe_divide(dividend: f64, divisor: f64) -> Result<f64, &'static str> {
// Your code here
// }
fn main() {
// Read the first input (dividend)
let mut dividend_input = String::new();
io::stdin().read_line(&mut dividend_input).expect("Failed to read line");
let dividend: f64 = dividend_input.trim().parse().expect("Invalid number");
// Read the second input (divisor)
let mut divisor_input = String::new();
io::stdin().read_line(&mut divisor_input).expect("Failed to read line");
let divisor: f64 = divisor_input.trim().parse().expect("Invalid number");
// TODO: Call safe_divide and use match to handle the Result
// Print the appropriate output based on the result
}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