3 ms·
You're right - that would suck if you couldn't do that! In rust, damn near everything is an expression - including `if` statements. So: let a = if let So
by Mouse47 9y ago
You're right - that would suck if you couldn't do that!
In rust, damn near everything is an expression - including `if` statements. So:
let a = if let Some(x) = check(param0) { x } else { return Err(""); };
Oh - I couldn't tell if you were aware by your post, but if you have a return type `T` and you want to compose it with an error type, you can use the type Result<T, ErrType>. This is functionally equivalent to having this:
>Maybe the last member of a type could correspond to "failure" by default (ie None or Err() in typical cases).
as a language-level feature, except it's opt-in. So functions that return `T` instead of `Result<T, _>` never return errors (besides panics, which are more-or-less 'fatal'), and that fact is obvious to the caller. That's really nice IMO.
- childintime 9y ago> let a = if let Some(x) = check(param0) { x } else { return Err(""); }; That's not DRY at all. BTW, by stating that Rust has no concept of failure, I meant to say the compiler doesn't have one, as it doesn't know that Err() in a type conveys an error. To automatically unwrap() something, I think it would have to know.
- steveklabnik 9y agoThis line is much more concise as let a = check(param0)?; or possibly let a = check(param0).map_err(|_| Err(""))?; depending.
- Mouse47 9y agoWait does that work? Unwrapping Options using `?`?
- steveklabnik 9y agoOh, I missed that it's an Option. That means that it won't work today, but https://github.com/rust-lang/rust/pull/42526 https://github.com/rust-lang/rust/pull/42526 landed, and is in beta. This means on the next release of Rust, code like this will work: fn try_result_some() -> Option<u8> { let val = Some(1)?; // Ok also works Some(val) } that is, using `?` on an Option in a function returning an Option. That being said, similar code will not yet work: fn try_result_some() -> Result<u8, Box<Error>> { let val = Some(1)?; Ok(val) } that is, using `?` on an Option in a function returning Result. This is because https://doc.rust-lang.org/nightly/std/option/struct.NoneError.html https://doc.rust-lang.org/nightly/std/option/struct.NoneErro... isn't stable yet.
- AlphaSite 9y agoI think what he is asking for is Swifts guard.