3 ms·
The 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 ?
by irishsultan 9y ago
The 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.
- irishsultan 9y agoIt does evaluate to something, try this if you don't believe me. fn try_option_some(param: Option<u8>) -> Option<u8> { if let Some(val) = param { Some(val + 1) } else { None } } fn main() { print!("{:?}\n", try_option_some(None)); print!("{:?}\n", try_option_some(Some(2))); }
- Manishearth 9y agoMy bad, I think I read this as let val = if .... by accident. Oops
- viraptor 9y agohttps://rustbyexample.com/flow_control/if_else.html https://rustbyexample.com/flow_control/if_else.html > if-else conditionals are expressions, and, all branches must return the same type.
- Manishearth 9y agoYeah; I misread the original code
- viraptor 9y agoSorry, it was written on a mobile. Yes, it should be "if let Some (val)" but I can't edit anymore.