43 ms·
It skips a block you'd need otherwise. Without it, you'd have to do something like: fn try_option_some() -> Option<u8> { if let val = Some(1) {
by viraptor 9y ago
It skips a block you'd need otherwise. Without it, you'd have to do something like:
fn try_option_some() -> Option<u8> {
if let val = Some(1) {
Some(val)
} else {
None
}
}
It's an early exit if the expression before is None/Error
- Sharlin 9y agoThere should really be a more real-world example, the current code (and your alternative version) is just redundant and equivalent to fn try_option_some() -> Option<u8> { Some(1) }
- lower 9y agoSuppose you have two functions fn f() -> Result<A, E> fn g() -> Result<B, E> Then you can write fn h() -> Result<(A,B), E> { let x = f()?; let y = g()?; Ok((x, y)) } rather than having to do something like fn h() -> Result<(A,B), E> { match f() { Ok(x) => { match g() { Ok(y) => Ok((x,y)), Err(e) => Err(e) } }, Err(e) => Err(e), } } (written from memory, please excuse syntax errors) What's new is that this also works with Option<A> now.
- zZorgz 9y agoAs others mentioned, it looks equivalent to using the try! macro (which I'm not sure this is supposed to replace?) Another sane alternative here is using and_then, map, etc. Writing from memory too: fn h() -> Result<(A, B), E> { f().and_then(|x| g().map(|y| (x, y))) } ..which seems to be a different style of control flow to choose from. On one hand, I suppose one may avoid using and_then with code dealing with side effects. On another hand, ? seems restricted to being used inside functions that have to return a a single type (like Result) they operate on.
- steveklabnik 9y ago? is explicitly a replacement for try!, yes. > functions that have to return a single type Well, all functions have to return a single type, though that type may be a composite type, like a tuple. Less pedantically, `?` lets you (well, will let you) unwrap values and convert their error cases between each other. So once the next round of stabilization happens, if you have a function that returns Results, you can mix ? on Options and Results in the body, and vice versa. And it can be extended for other types too. Basically, it's an early return "protocol" if you will.
- zZorgz 9y agoBy single type, I meant to hint not being able to mix ? on Options and Results in the body, but good to know that's soon possible! Though you still can't, eg, use `?` in main()
- steveklabnik 9y agoThat's coming as well!
- zZorgz 9y agoInteresting. Looking at the proposal it seems specific to main() and not any void returning function, by automatically picking an exit status. I suppose I worry the construct has a lack of control (log diagnostics, exit status, cleaning, etc) when bailing and can’t handle eg continue, break too.
- steveklabnik 9y agoexit status and cleaning should be just fine, logging or something else would need to not do it, yeah. continue and break would be weird outside of loops.
- zZorgz 9y agoAlso regarding an "early return protocol", I'd also be curious for continue, break, any ! type expression. For one of the Rust projects I worked on, I wrote an unwrap macro on Option that takes a secondary ! argument.
- masklinn 9y agoTechnically it also applies a conversion operator to the "error" value (a no-op for the Option -> Option case, but it can be otherwise for Option -> Result or Result<T, E> -> Result<T, F>
- Manishearth 9y agoYour example is confusing, too; you've removed the code after the try? so it's not equivalent to the example in the blog, and because it's a single thing there's no early return anymore, thoroughly obfuscating what it is that try did :|
- irishsultan 9y agoUnless I'm missing something it's exactly equivalent (and likely to compile to the same code), after all both check whether there is a value to extract and immediately return None if there isn't, both return Some(val) if there is a value to extract. If you added extra code to manipulate things then that single if would still be enough, just place everything that happens after the extraction inside the success branch of the if statement.
- Manishearth 9y agoYou are missing something, it won't compile at all. You're missing a Some(val) at the end. Now you could remove the `if let val` as well to make it compile, but then that obfuscates what the ? operator was doing there.
- irishsultan 9y agoThe error seems to be that `if let val = Some(1)` should be `if let Some(val) = Some(1)` (i.e. the pattern match should have extracted val, which is what the ? operator does as well). I think it would have been much clearer to have 1 function which took a parameter of type Option<u8>, then did something with it after extracting with ?, then call it twice, once with Some(1), once with None. In addition I'd probably do something with val (e.g. add 1). And to prevent easy conversion to the if statement you could make the early return explicit by doing the extraction somewhere in a loop (so that you can't get at it with nested if statements).
- Manishearth 9y agoNo, that, _and_ that if let ... {} doesn't evaluate to anything; your function doesn't evaluate to anything even though it has a stated return type of Option. I mean, this isn't hard to check, try compiling it. I was saying it's misleading not only because it's wrong, but also because even if something is equivalent if you're trying to show how a feature works you want equivalent code that cleanly maps to the original; and isn't further reduced.