This is my first attempt at participating in the language design process. Hope I’m doing it right – meta-feedback welcome!
Motivation
- Making the simple things easy, but the hard things possible
- Allowing evolution of APIs with source compatibility
- Bite off one piece of the optional + default + named arguments improvements
- Lots of people want it
Proposed solution
fn adder(x: int, b: Option<int>) -> int {
x + b.unwrap_or(1)
}
fn main() {
println!("added {}", adder(5));
}
The compiler will fill in None
for any omitted function parameters if and only if they are of type Option
. This nicely complements impl From<T> for Option<T>
.
Drawbacks
- Default values have to be specified in the function, at the cost of slightly more code there. This seems like an acceptable cost given the limited weight (in terms of ergonomics) of making this change.
- Makes the
None
arguments implicit, which makes it slightly harder to see what’s going on.
Alternatives
- Default arguments (
fn adder(x: int, b: int=1) -> int
) require a bunch of syntax changes. We would need to impose more restrictions (only allow statics has been thrown around in the past), and the syntax looks kind of ugly in my mind, because there’s not really a natural order from name to type and value. - Builder APIs (requires no changes) can be used. However, I’d argue that for many uses this is much more wordy, and requires more work in looking up the proper API calls. Also, I’m guessing it would perform worse at a micro-level, given the amount of function calls.
Unresolved issues
- There might be some interaction with named arguments in the future. To me, this proposal seems like a clean first improvement that will most likely not make named arguments harder, and hopefully makes it easier, so I thought I’d raise this pre-RFC for optional arguments only.
- Undoubtedly others can come up with more!
Further reading
- Default arguments and keyword arguments, original rustc issue from Jun 2013, with accompanying design discussion in an Etherpad
- Named + optional parameters, Reddit thread from May 2014
- Struct Sugar RFC issue and precursor i.r-l.o discussion, from Oct 2014
- optional parameters RFC from Jul 2014
- Default and positional arguments RFC from Sep 2014
- Wishlist issue in RFCs repo for keywords arguments, optional arguments and/or variable-arity argument lists from Sep 2014
I confess to not having read through all of it, but I have skimmed through them and looked at outcomes and resolutions so far. A bunch of these were closed based on an impending 1.0 deadline and wanting to do this in a backwards-compatible ways. In any case, I couldn’t find anything that clearly invalidates the proposal in this pre-RFC.