4 ms·
I agree. I’ve seen a few libraries (I can’t remember which) instead take the approach of a constructor that takes a single-use struct as an argument. The struct
by paulgb 5y ago
I agree. I’ve seen a few libraries (I can’t remember which) instead take the approach of a constructor that takes a single-use struct as an argument. The struct implements Default and all of its members are public. You can then use ..Struct::default() to splice in the default values, and override only the values you want to set.
It ends up being an approximation of named optional arguments, albeit with a somewhat more clunky syntax.
- wmanley 5y agoI would quite like to see some syntax sugar around this. If we could elide the type and made `...` equivalent to `..Default::default()` it would be a lot closer to kwargs without having to introduce any new "real" features. So we could write: f(arg1, arg2, _ {name: "Hello", address, ...}) instead of f(arg1, arg2, MyKwargs {name: "Hello", address, ..Default::default()} Using a struct for this feels natural as you get forwarding and non-exhaustiveness for adding additional fields for free.
- nicoburns 5y agoI would like this plus the ability to specify per-field defaults on structs like struct Foo { bar: String, // No default baz: Option<u32> = None, } I think this would give us 90% of what I would want from first-class named parameters.
- estebank 5y agoI'm looking for the time to write exactly that RFC. The parser, for what is worth, already parses that syntax for error recovery :) If you're interested, this is the last public conversation I had about these: https://internals.rust-lang.org/t/pre-pre-rfc-syntactic-sugar-for-default-default/13234 https://internals.rust-lang.org/t/pre-pre-rfc-syntactic-suga...
- skohan 5y agoOr you could just have named arguments with defaults, which is a highly ergonomic and well-tested solution to this problem.
- seritools 5y agoYeah, I've seen it called the Init Struct pattern: https://xaeroxe.github.io/init-struct-pattern/ https://xaeroxe.github.io/init-struct-pattern/
- paulgb 5y agoThat reminds me of a library where I’ve seen it in use: wgpu. For example https://docs.rs/wgpu/0.11.0/wgpu/struct.TextureViewDescriptor.html https://docs.rs/wgpu/0.11.0/wgpu/struct.TextureViewDescripto...