by aazaa · 5y ago · 0 comments
I'm surprised the article doesn't mention Default:
https://doc.rust-lang.org/std/default/trait.Default.html
It can be combined with the rest pattern to yield something very similar to the solution the author is after.
https://stackoverflow.com/questions/19650265/is-there-a-fast...
The caller needs to know that the input struct implements Default.
And you would need one input struct per function (if default values differ).
Are there better ways or is it planned to introduce something like default parameters?
It's a question of taste, but the builder pattern can be considered a “better way”, because of how clunky the use of Default can be.
You would prefer an API with easier to read, documented builders than the ..Default::default() call.
struct Parameters {
non_optional_parameter_1: Foo,
non_optional_parameter_2: Bar,
extra_options: ParametersWithDefault,
}
#[derive(Default)]
struct ParametersWithDefault {
...
}
which is kind of annoying but not the end of the world. use module::{ foo, Parameters, ParametersWithDefault };
fn bar() {
foo(Parameters {
non_optional_parameter_1: Foo,
non_optional_parameter_2: Bar,
extra_options: ParametersWithDefault {
optional_param: Baz,
...Default::default(),
}
});
}
is a far cry in ergonomics from: use module::foo;
fn bar() {
foo(_ {
non_optional_parameter_1: Foo,
non_optional_parameter_2: Bar,
optional_param: Baz,
..
});
}
Even just having to import the extra structs (and lookup the names) is a massive pain. Especially if you need to change to use a slightly different function.More details about this and what else is lacking in Rust compared to Kotlin:
https://medium.com/@cedricbeust/what-rust-could-learn-from-k...
Also, this doesn't help at all for function invocation, which is still very cumbersome in Rust in the absence of default parameters, named parameters, and overloading.