is_ok() and is_err()
Part of the Logic & Flow section of Coddy's Rust journey — lesson 44 of 66.
Sometimes you need to quickly check whether a Result represents success or failure without extracting the actual values. Rust provides two convenient methods for this: .is_ok() and .is_err().
Both methods return a boolean value, making them perfect for simple conditional checks. The .is_ok() method returns true if the Result is Ok, and false if it's Err. The .is_err() method works in reverse:
let success: Result = Ok(42);
let failure: Result = Err("Something went wrong");
if success.is_ok() {
println!("Operation succeeded!");
}
if failure.is_err() {
println!("Operation failed!");
}These methods are particularly useful when you only need to know the outcome status without caring about the specific values inside. Unlike match, they don't consume the Result, so you can still use it afterward.
Challenge
EasyYou will receive two inputs. The first input is a number (as a string), and the second input is a status indicator (success or failure). Create a Result<i32, &'static str> based on the status. If the status is success, create an Ok containing the parsed number. If the status is failure, create an Err with the message "Operation failed". Use .is_ok() and .is_err() to check the result status and print the appropriate message.
Requirements:
- Read the first input (number) and trim whitespace
- Parse the first input to
i32 - Read the second input (status) and trim whitespace
- Create a
Result<i32, &'static str>variable:- If the status is
success, assignOk(parsed_number) - If the status is
failure, assignErr("Operation failed")
- If the status is
- Use
.is_ok()to check if the result is successful:- If true, print:
Success detected
- If true, print:
- Use
.is_err()to check if the result is an error:- If true, print:
Error detected
- If true, print:
Input:
- First line: A number (e.g.,
42) - Second line: Either
successorfailure
Output:
- If the status is
success:Success detected - If the status is
failure:Error detected
Cheat sheet
Rust provides two methods to check the status of a Result without extracting its values:
.is_ok()- returnstrueif theResultisOk,falseotherwise.is_err()- returnstrueif theResultisErr,falseotherwise
let success: Result<i32, &str> = Ok(42);
let failure: Result<i32, &str> = Err("Something went wrong");
if success.is_ok() {
println!("Operation succeeded!");
}
if failure.is_err() {
println!("Operation failed!");
}These methods are useful for simple conditional checks when you only need to know the outcome status. Unlike match, they don't consume the Result, allowing you to use it afterward.
Try it yourself
use std::io;
fn main() {
// Read the first input (number)
let mut number_input = String::new();
io::stdin().read_line(&mut number_input).expect("Failed to read line");
let number_input = number_input.trim();
// Parse the number to i32
let parsed_number: i32 = number_input.parse().expect("Failed to parse number");
// Read the second input (status)
let mut status = String::new();
io::stdin().read_line(&mut status).expect("Failed to read line");
let status = status.trim();
// TODO: Create a Result<i32, &'static str> based on the status
// If status is "success", create Ok(parsed_number)
// If status is "failure", create Err("Operation failed")
// TODO: Use .is_ok() and .is_err() to check the result and print the appropriate message
}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