News for hackers. Stuff that matters.
Re:Optional If Expressions by _flux on Saturday April 15, 2023 @03:50AM (#35578558)
I don't like the "then" branch having a different type than what it actually returns. If you need to add an "else" branch you then also need to touch what the "then" branch returns. Seems like spooky action at distance.

I could maybe bear with "let foo = if true { Some(42) } /* else omitted */;" that would then give the automatic "None" else branch automatically. Bonus: it works the same with and without type annotations.

Re:Optional If Expressions by conaclos on Saturday April 15, 2023 @05:11AM (#35578939)
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 }`.

Re:Optional If Expressions by masklinn on Saturday April 15, 2023 @06:05AM (#35579162)
Doesn'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)`.
Re:Optional If Expressions by _flux on Sunday April 16, 2023 @07:25AM (#35589063)
Unless you want to return from within the filter with some error return code, or call an asynchronous function.
Re:Optional If Expressions by _flux on Sunday April 16, 2023 @07:29AM (#35589077)
Currently 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?

Re:Optional If Expressions by tempodox on Saturday April 15, 2023 @05:15AM (#35578956)
Agreed. I find Rust has already too much magic as it is.