Created
February 3, 2026 22:51
-
-
Save malcolmgreaves/09b91070dcc9276d78191560edf9debd to your computer and use it in GitHub Desktop.
[rust] Turn a `Result<T,T>` into a `T`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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