Skip to content
maslina524 edited this page Apr 20, 2026 · 2 revisions

Error handling with the Result type.

Result[T, E] is the type used for returning and propagating errors.

Method overview

In addition to working with pattern matching, Result provides a wide variety of different methods.

Classmethods

  • ok returns Result with the value in Ok
  • err returns Result with the value in Err

Querying the variant

The is_ok and is_err methods return True if the Result is Ok or Err, respectively.

Extracting contained values

These methods extract the contained value in a Result<T, E> when it is the Ok variant. If the Result is Err:

  • expect panics with a provided custom message
  • unwrap panics with a generic message
  • unwrap_or returns the provided default value
  • unwrap_or_else returns the result of evaluating the provided function

This method work the other way around if Result<T, E> is the Err variant:

  • unwrap_err panics with a generic message

Transforming contained values

  • map transforms Result<T, E> into Result<U, E> by applying the provided function to the contained value of Ok and leaving Err values unchanged
  • map_err transforms Result<T, E> into Result<T, U> by applying the provided function to the contained value of Err and leaving Ok values unchanged
  • map_or applies the provided function to the contained value of Ok, or returns the provided default value if the Result is Err
  • map_or_else applies the provided function to the contained value of Ok, or applies the provided default fallback function to the contained value of Err

Examples

Creates a Result<T, E> with the Ok and Err variants and safely extracts the value:

from rustify import Result

ok = Result.ok("Hello World")
err = Result.err("I'm a error")

print(f"{ok.unwrap()}")                 # Hello World
print(f"{err.unwrap_or("Unwrap Err")}") # Unwrap Err

Clone this wiki locally