3 ms·
Rust could introduce a new trait similar to Default: let's say ElseDefault. Every type implementing this new trait could return the default value of the type of
by conaclos 3y ago
Rust could introduce a new trait similar to Default: let's say ElseDefault. Every type implementing this new trait could return the default value of the type of if branch when the else branch is missing and is triggered. Option<V> could implement ElseDefault and returns None as default value.
This could make `if x { Some(42) }` equivalent to `if x { Some(42) } else { None }`.
- masklinn 3y agoDoesn't seem very useful though, when you can just write that out, or use `bool::then`, or use some weird combinator on `Option` e.g. `Some(42).filter(|_| x)`.
- _flux 3y agoUnless you want to return from within the filter with some error return code, or call an asynchronous function.
- _flux 3y agoCurrently we can write fn foo() -> () {} And it returns an instance of (). I guess the same mechanism could be generalized for any value with, like you said, a trait like MissingValueDefault. That would then also work with the omitted else branch. I'm not sure if there are some difficulties in calling different code based on type inference results, though. Are there other situations where that happens?