I started noticing that functions that return Result<(), _>
are quite common, and most of the time they end up with a Ok(())
, which feels heavy. I mean, there is the try!
macro with its very convenient ?
shortcut which makes using Result
so painless, but at the end you have to add something that feels like the compiler could have figured out alone (or that is used so often that it could even be a special case). I also saw some discussions about it, where some people argued for making it a special case (ie. writing nothing and the compiler guesses the Ok(())
on its own), and some arguing against it saying that, in Rust, most of the things are explicit, and that this is a good thing.
Tangentially, I also read about the proposal to make Default
derivable for enums. And that's when I got an idea. Wouldn't it be possible to add a "default function modificator" (the name isn't very good but I couldn't figure out something better), similar to the visibility keyword, that would work as following: given a type T
such that T: Default
, and I am writing a function func
such that func: fn(_) -> T
, then I could add the default
(or maybe just def
?) keyword before fn
:
default fn func(_) -> T {
...
}
such that, for each branch of func
where nothing is returned, an implicit T::default()
is returned instead.
This would be quite convenient, while still making it explicit and, very importantly, not enabled "by default" for every function, since that could screw up silently someone's code (ie. they forgot to return somewhere, and if that feature would be enabled for every function, the compiler would silently accept it and behave in a way that was not what the user expected).
This would also avoid creating a special case only for Ok(())
, which is good because nobody likes special cases, and everybody likes meaningful language features that are useful in lots of places.