Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Created February 3, 2026 22:51
Show Gist options
  • Select an option

  • Save malcolmgreaves/09b91070dcc9276d78191560edf9debd to your computer and use it in GitHub Desktop.

Select an option

Save malcolmgreaves/09b91070dcc9276d78191560edf9debd to your computer and use it in GitHub Desktop.
[rust] Turn a `Result<T,T>` into a `T`.
pub trait Resolve<T> {
fn resolve(self) -> T;
}
impl <T> Into<T> for Result<T,T> {
fn resolve(self) -> T {
match self {
Ok(value) => value,
Err(err) => err,
}
}
}
fn main() {
let result: Result<bool, String> = Ok(true);
// let result: Result<bool, String> = Err("hello world".into());
let code = {
result
.map(|b| if b { 1 } else { 0 })
.map_err(|s| if s.len() == 0 { 2 } else { 3 })
// : Result<i32, i32>
.resolve()
};
// : i32
println!("code: {}", code);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment