Allow ignoring struct name in function calls

What do you think about syntax like

struct FooParams {
    a: i32,
    b: Option<i32>
}

fn foo(params: FooParams) {
  …
}

// Current syntax
foo(FooParams { a: 10, b: None });

// proposed equivalent (both should be accepted)
foo({ a: 10, b: None });
// or
// foo(_ { a: 10, b: None }); // but I dislike it

It would provide “keyword arguments” in Rust 1.0.0 without any breaking changes.

PS To be clear, this syntax should work iff there is no ambiguity about selected struct, so

fn foo<T>(params: T) where … {
    …
}

foo({});

would be illegal as this would need some kind of guessing/casting between types.

Reasons:

This is the same way what JavaScript is doing it (or at least it is similar). It is IMHO really worth consideration as I don’t see any reason for Rust to have “keyword arguments” as we have enough tools to make it happen without additional syntax.

1 Like

This is totally backwards compatible to add, right? If so, there’s basically 0% chance of it making it into 1.0 at this point in time.

Ok, maybe not in 1.0.0, but IMHO still worth consideration as alternative to keyword arguments.

Unfortunately, {....} is a valid expression so, until you reach the first name: value, it’s a little ambiguous (and {} could either be () or SomeStruct{} but not a tuple).

You could use foo{} but that would be ambiguous for the reader. Personally, I have no problem with foo("a", 1234, _{name: true}) (a little verbose but very clear and flexible). Additionally, this would allow for things like:

pub struct Bar {
   a: bool,
   b: bool,
}
impl Bar {
    pub fn new() -> Self {_{
        a: true, b: true
    }}
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.