Named Arguments are Just Structs: Anonymous Struct Parameters

There's been a recent round of posts on named arguments in Rust: Botahamec's Named and Optional Arguments are Awesome, Steve Klabnik's Arguing about arguments, and Matthias Endler's We Have Named Arguments at Home. I've taken my original thoughts from 2016 and written up a design that starts from Endler's premise: Rust already has a named, reorderable, defaultable construct, the struct. The design removes the ceremony that makes using a struct this way less appealing.

TL;DR: it adds two pieces of syntax. struct { .. } is an anonymous struct type in parameter position, and _ { .. } is a struct literal or pattern whose type is inferred. Then some named argument sugar.

fn crop(img: &Image, struct {
    width: u32,
    height: Option<u32> = None,
    x: u32 = 0,
    y: u32 = 0,
}) -> Image { .. }

crop(&img, _ { width: 200, .. });

Read the full post:

25 Likes

I’m concerned about the ABI implications of this proposal. Structs are often passed as pointers rather than being passed in registers, for example. I think anonymous struct types declared in function item signatures should at least have a special representation that unpacks the fields for the function call ABI (similar to what rust-call does for tuples). Perhaps it can even be turned into a general purpose struct representation (repr(unpacked), perhaps?).

Secondarily the semver implications are strange. Default field values are a bit of a footgun because you can still construct them exhaustively. I’m happy with only getting the anonymous struct syntax without default field values, they seem pretty orthogonal.

11 Likes

Firstly, thank you for presenting this all so clearly!

Of the things you've presented, I would find parameter_type_elision most useful in my existing code - that would clean up a bunch of things where I'm using multiple structs for named parameters already, and it's already useful to have named structs for those parameters. That, on its own, would be a nice improvement for my use cases today (and we have enough parameters in the structs that ABI implications aren't a concern).

3 Likes

This is indeed the approach that I would prefer to go with, specially because it answers questions around FFI and it is a composition of features that are useful individually, and it still leaves the door open for future purely syntactic sugar, like a method with a single non-self anon struct argument being callable with foo.bar { baz, qux: 42, .. } or foo.bar(baz, qux: 42, defaulted: _).

6 Likes

Also really helps for running things through closures, too!

4 Likes

Is this compatible with this?

let closure = |aggregate: struct { width: u32, height: Option<u32>, x: u32, y: u32 }| crop(img, aggregate);

Why or why not?

2 Likes

So I do think the initial version of this feature could support anonymous structs in closures like you show here. However, until we decide on how this feature expands into full blown record types (or if it ever does), that type is probably just going to be treated as a completely different struct from the one that crop takes. So you'd still have to call it with crop(img, _ { width, height }).

I have some preliminary thoughts on record types, but that's a much larger change to Rust than even this, and there's more history to dig through there and case studies in other languages than I'm fully versed in.

4 Likes

Thanks, just want it thought about; I have no opinion on what is "right" at the moment, but I have an eye for corner cases :slight_smile: .

1 Like

Named arguments are just structs, and unnamed arguments are just tuples. Just like we have tuple-variants and struct-variants of enums, we could by analogy have tuple-functions and struct-functions:

f(1, 2, 3); // tuple function
f{a: 1, b: 2, c: 3}; // struct function
9 Likes

This was actually my original line of thinking back in 2016, but I doubt the broader community will accept it (maybe I'm wrong).

The biggest issue with this in my opinion is definitions:

fn f { x: i32 } { todo!() }  // not too bad
fn g(a: i32) { x: i32 } -> i32 { todo!() }  // getting worse
// kinda a mess
fn h(
    a: i32,
    b: i32,
) {
    x: i32,
    y: i32,
} {
    todo!();
}

That said, I personally still kinda like it.

Either way, the core idea remains, and this is mostly a discussion of the named_parameters sugar.

3 Likes

I'd just disallow mixing positional parameters with named parameters.

Similarly, enum variants don't allow mixing both at the same time:

enum E {
    A(i32, i32), // OK
    B{x: i32}, // OK
    C(i32, i32){x: i32}, // no, that's not allowed
}
let a = E::A(1, 2); // OK
let b = E::B{x: 3}; // OK
let c = E::C(1, 2){x: 3}; // nope

So I think functions with {} arguments would naturally extend what we already have for enum constructors.

5 Likes

That doesn't address one of the most core use cases for named arguments though. A function which takes some traditional positional arguments and acts like a normal function, but then takes a bunch of defaulted optional named options.

3 Likes

And then...

f(1, 2, 3);

// Same thing
f { 0: 1, 1: 2, 2: 3 };
5 Likes

What's the improvement from not passing the arguments as normal ones? Seems that we can somehow pass the anonymous struct parameters to another function as a 'bulk', but if so we have to find out a way to let compiler know whether passing objects is OK.

Even worse, it seems that there's no way to set a default value for such structures.

1 Like

I think that if a function has some named parameters, it might as well name all the parameters. Again, this is similar to what we already have with enums variants.

With this approach, struct enum variant constructors would become regular functions, just like tuple variant constructors are regular functions.

The defaulted values feature is something that might be useful for all structs, not just for function arguments, so the notation should be the same as whatever notation regular structs might use for defaulted values.

3 Likes

Assuming I understand the proposal correctly, the point is that all of this ends up being syntax sugar for things you can write today with a bit of extra work.

So, starting at the bikeshed named arguments syntax, you might write:

pub fn foo(bar: u32, baz: &str; idx: usize = 0, limit: Option<usize> = None) -> Result<String, Error>
// called as:
{
    let out = foo(42, "fish", idx: 2, ..local_defaults)?;
}

This is syntax sugar for an anonymous struct:

pub fn foo(bar: u32, baz: &str, struct { idx: usize = 0, limit: Option<usize> = None}) -> Result<String, Error>
// called as:
{
    let out = foo(42, "fish", _ { idx: 2, ..local_defaults })?;
}

And in turn, this is syntax sugar for an existing construct where you have to make up a name:

#[derive(Default)]
pub struct KeywordParams {
    pub idx: usize,
    pub limit: Option<usize>,
}

pub fn foo(bar: u32, baz: &str, KeywordParams { idx, limit }: KeywordParams) -> Result<String, Error>
// called as:
{
    let out = foo(42, "fish", KeywordParams { idx: 2, ..local_defaults })?;
}

// Or, using the optional `#![feature(parameter_type_elision)]`
pub fn foo(bar: u32, baz: &str, KeywordParams { idx, limit }) -> Result<String, Error>
// The line above is just syntax sugar for the more verbose
// version where `KeywordParams` is repeated

Any optimizations to Rust's ABI that improve the final case (which is one that already exists in Rust code) also improve the ABI for the syntax sugar variants that this proposal adds. IMO, that's what makes this proposal a compelling way to handle named and defaulted arguments - it's not creating something new, with new ABI optimizations needed, when it can instead build on something that already exists.

8 Likes

Your suggestion is very beautiful, but there are problems that occur after you work Struct anonymously, which is difficult to determine the name of the values and their places for the user who does not know. What did I do, but my suggestion is to make Struct clear to the user, to the programmers, and developers, to tell you about the values, their arrangement, shape, names and number, and this makes programming easier and better, and even at the time of using it, all you have to do is added inside impl, the things that you want, such as new, and it takes care of putting the values, but if you want to change one value, for example, you can make functions to do that and save you and we have to work


#[derive(inFn)]
struct haql {
    width: u32,
    height: Option<u32> = None,
    x: u32 = 0,               
    y: u32 = 0,            
} 
impl haql {
 fn new (…){…}
…
}

fn crop ( img : &Image , haql){…}


crop (..,haql::new());



 
1 Like

This is actually what I feel like would make most sense as well, and it could help in the argument-pass-through case, if we could name that type via an assoc type on Fn* traits.

1 Like

You can almost get there on nightly, but by making the struct callable:

#![feature(unboxed_closures)]
#![feature(fn_traits)]

struct Image;

#[derive(Debug, Default)]
#[allow(unused, non_camel_case_types)]
struct crop {
    width: u32,
    height: Option<u32>,
}

impl std::ops::FnOnce<()> for crop {
    type Output = Image;
    extern "rust-call" fn call_once(self, _args: ()) -> Image {
        dbg!(self);
        Image
    }
}

fn main() {
    crop{ width: 200, height: None}();
}

Optional arguments are possible too but using default is currently more verbose:

#[allow(non_upper_case_globals)]
const crop: crop = crop { width: 0, height: None };

crop{ width: 200, ..crop}();

And now that I write that out it does look very repetitious.

4 Likes