Skip to content

Instantly share code, notes, and snippets.

@novafacing
Created October 17, 2023 23:13
Show Gist options
  • Save novafacing/6e087e5a62301a5b5c5a3fbd95263356 to your computer and use it in GitHub Desktop.
Save novafacing/6e087e5a62301a5b5c5a3fbd95263356 to your computer and use it in GitHub Desktop.
Rust Option/Result conversion functions

I used to have a site bookmarked with a table of all these functions, but the link is dead. Here's a matrix of Option and Result conversion functions. These become second nature once you have used Rust for any significant length of time, but it's useful to have a table reference.

For each of the below:

  • T is the value possibly contained in an input Ok Result or Some Option.
  • U is a new value created by transforming or replacing an input T. Note that when U appears in methods like map, U ?= T, for example by calling Result<T, E>.map(|t| t)
  • E is the error possibly contained in an input Err Result
  • F is a new value created by transforming or replacing an input E. Note that when F appears in methods like map, F ?= E, for example by calling Result<T, E>.map_err(|e| e)
Input Type Method Output Type Notes
Result<T, E> and Result<T, E> Eager, use and_then instead.
Result<T, E> and_then Result<T, E>
Result<T, E> err Option<E>
Result<T, E> map Result<U, E>
Result<T, E> map_err Result<T, F>
Result<T, E> map_or U Eager, use map_or_else instead.
Result<T, E> map_or_else U
Result<T, E> ok Option<T>
Result<T, E> or Result<T, F> Eager, use or_else instead.
Result<T, E> or_else Result<T, F>
Input Type Method Output Type Notes
Option<T> and Option<U> Eager, use and_then instead.
Option<T> and_then Option<U>
Option<T> filter Option<T>
Option<T> map Option<U>
Option<T> map_or U Eager, use map_or_else instead.
Option<T> map_or_else U
Option<T> ok_or Result<T, E> Eager, use ok_or_else instead.
Option<T> ok_or_else Result<T, E>
Option<T> or Option<T> Eager, use or_else instead.
Option<T> or_else Option<T>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment