Code Logo

Check Success with is_ok()

Published at25 Jul 2026
Rust Functions Easy 0 views
Like0

Write a Rust function that takes a Result and returns true if the Result is Ok (success) using the is_ok() method. The is_ok() method returns true for the Ok variant and false for the Err variant, without consuming or unwrapping the Result.

Result is Rust's type for fallible operations. The is_ok() method is the safest way to check if a Result represents success. Unlike unwrap() which panics on Err, or match which requires handling both arms, is_ok() simply returns a bool. This makes it ideal for quick checks where you don't need the actual value.

The is_ok() method is complemented by is_err() which returns true for the Err variant. Both methods are zero-cost abstractions that compile to simple discriminant checks on the Result's enum tag. They are the preferred way to check Result types without unwrapping when only the success/failure status is needed.

Time complexity is O(1) as is_ok() is a simple enum variant check. Space complexity is O(1). The method compiles to a conditional instruction without any branching overhead beyond the enum tag check.

Edge cases include Ok with zero or default values (is_ok still returns true), Err with various error types (always returns false), and ensuring the method does not consume the Result so it can be used multiple times.

Example Input & Output

Example 1
Input
Ok(0)
Output
true
Explanation

Ok with zero is still Ok

Example 2
Input
Err("x")
Output
false
Explanation

Err with short message

Example 3
Input
Ok(100)
Output
true
Explanation

Ok with large value

Example 4
Input
Ok(42)
Output
true
Explanation

Ok result returns true for is_ok

Example 5
Input
Err("fail")
Output
false
Explanation

Err result returns false for is_ok

Algorithm Flow

Recommendation Algorithm Flow for Check Success with is_ok()
Recommendation Algorithm Flow for Check Success with is_ok()

Solution Approach

Check if a Result value is Ok (success) using the is_ok() method. Returns true if the result contains a success value, false if it contains an error. This is the simplest way to check success status without pattern matching.

fn solution(r: Result<i32, String>) -> bool {
    r.is_ok()
}

is_ok() pairs with is_err() for checking failure. To extract the success value, use unwrap() (panics on Err) or expect() (custom panic message). For safe extraction, match on Ok/Err or use ok()/err() to convert to Option.

Time complexity is O(1), space complexity is O(1).

Best Answers

rust - Approach 1
fn solution(val: Result<i32, String>) -> bool {
    val.is_ok()
}