By struct constructor I'm referring to the let a = A { b: c };
syntax.
Rust already supports inference of types based on subsequent usages, so it might be nice to infer the struct name as well:
struct OneLongStructName { a: i32, b: i32, c: i32 }
fn bar(foo: OneLongStructName) {}
fn main() {
bar(_ {a: 1, b: 2, c: 3});
}
This would be useful to achieve something like JavaScript's (TypeScript in particular) named-parameters-by-object pattern, like this:
function ajax(options: jQuery.AjaxOptions) {}
ajax({ url: "https://example.com" })
This is especially useful when the parameter type has a long signature (including generics), or requires imports (which reduces coding fluency).
Underscore
I suggested _()
or _{}
instead of ()
or {}
because of the potential ambiguity with tuple expressions or block expressions.
Underscore is the idiomatic "infer type" identifier in type context, so it is apparent that _
is there to replace an omitted type name.
Functions rarely directly require passing in a unit struct (usually it's passed to specify a type parameter, which cannot be inferred anyway), so this RFC should not cover unit struct construction.
Enums
It might also be useful to have _::EnumVariant
syntax when it's clear that the context requires an enum type, but this is the scope for another RFC. I remember reading a similar RFC before. This thread appears to be related.
Patterns
It might be useful to be able to destructure a known type using a similar syntax e.g. let _ { a, b, c} = foo;
, but this is also out of scope.