Named Arguments are Just Structs: Anonymous Struct Parameters

This is also still clearly a function call unlike

which makes it much less problematic to teach and retrofit into the language.

When you add positional arguments to that, they have to come last at the callsite, but with just anonymous struct definitions we can do:

#[named_arguments::named_arguments]
pub fn crop(count: u32, { width: 200, height: None, .. }) {...}

fn main() 
{
    crop{width, height, ..}(3); 
}

This means the named arguments MVP doesn't need to include struct literal inference, but it would be a nice to have.

like the idea of using .. in the anonymous functions struct to imply #[must_default_construct] or whatever we decide to call the attributes for a non_exhaustive structs that can and must be defaulted.

1 Like

That would be very neat, but I think it's too late to allow name { ... } to have arbitrary side-effects -- there are probably already macros relying on this. Putting brace structs into the value namespace will also break tons of stuff.

This is on my list of Rust 1.0 "if I had a time machine" regrets.

3 Likes

Yea, if only... but I tend to agree, which is why I pivoted from the idea I started with a decade ago (time flying!) and landed here.

2 Likes

I really like the piecewise approach here, reaching the final goal with several widely-applicable features.

For elided struct patterns, it seems there's a conceptual collision between mut_restrictions on fields and mutable bindings. I assume anonymous structs are so short lived that there's no need for restrictions in the elided struct syntax, just pointing out a question that others may have.


The elided parameter types section seems very useful, though there does seem to be an asymmetry of pattern vs type when combining them. For non-Copy types the & in the pattern &Point { .. } no longer "undoes" a ref in this condensed form.
The post states that the condensed form short for #2 below, but is it possible to specify #1 as well?

  1. fn f(Point { x, y }: &Point)
  2. fn f(&Point { x, y }: &Point)

More specifically for an externally defined non-Copy struct:
struct Person { age: u32, name: String }
If you're passing &Person with elided parameter types, to avoid a compile error for moving out of name would you be forced to use &Person { ref name, age }: &Person instead of the (newer?) match ergonomics version Person { name, age }: &Person?

3 Likes

Thanks for the thoughtful reply.

Not going to lie, I didn't even know about that line of work. My gut reaction is that anonymous structs simply don't get mut_restrictions, since I wasn't planning on providing a way to impl <anon struct> so the API is very much limited to what you can do with the fields directly. The anonymous struct is tied to its function, so it gets its visibility and restrictions to follow, because if you made something like this:

pub fn foo(struct { mut(crate) x: u32 }) {}

You would have no way to call it in foo's pub context, since:

Further, astruct, union, or enum variant containing fields with an associated MutRestriction may not be constructed with struct expressions unless all fields are unrestricted in the present scope

Technically, right now I don't think they collide since there's no bare mut restriction AFAICT, but it's left open:

  • impl and mut could be usable without a path if deemed necessary. This behavior would be identical to omitting the keyword entirely.

So I agree, this is bumping up against that a bit, and while it might not technically conflict, it's a bit awkward. I also would like to leave the door open for future work on more generalized record types if that ever moves forward, and then the argument might not be an anonymous struct tied directly to the function anymore.

Needs deeper thought I feel, but I don't feel it'll be impossible to overcome, since this is really just a question of how to address the pattern elision in function definitions I think.


Both &Person { ref name, age }: &Person and Person { name, age }: &Person would still work as they do today, since you're not eliding anything, but you could also now write:

fn foo(&Person { ref name, age })

Which is literally just sugar for the same &Person { ref name, age }: &Person. However, Person { name, age }: &Person simply cannot be elided since the pattern and the type are different.

4 Likes

I like this approach but it has some issues that I think are solvable. One of the important properties of default paratmeters is that you can add more parameters later without breaking existing code. So requiring an additional parameter that will be just _{} is still problematic if the function didn't have it to begin with.

This can be solved by introducing pub trait ImplicitDefault: Default {} which makes the compiler call default() to obtain the value of last parameter of a function call if explicit one isn't passed. Additionally, it seems the anonymous struct should be generated as #[non_exhaustive], to force people use the .. syntax. Or perhaps, allow creating the struct even when it's missing by filling in the parameters. I suspect this can be again made into a trait using custom field projections.

2 Likes

Can we do a crater run to check this?

EDIT: or a least have foo{named, arguments} in the next edition (and foo(_{named, arguments}) for all the previous editions)?

1 Like

Regarding #[non_exhaustive], if you write struct{ foo: i32 = 3}, it's not (so can but doesn't have to be constructed with ..), and struct{ foo: i32 = 3, ..}, would be (so must be constructed with trailing ..).

1 Like

I may not be exactly in the loop here, excuse me,

but if it gets to the point where the user considers optional arguments I'd very much opt for a builder struct.

Someone here probably suggested this already so I'm adding my voice for that

1 Like

Without getting into a long debate about when to use named parameters vs builder patterns... first just how did you feel about the std::fs::copy example?

Builder patterns are great, especially when you need to do runtime logic in the calls, but they are heavier and named arguments are nice too IMO.

Does this mean you now have more options for how you want to represent your API, yes. Does that mean the ecosystem will have some people preferring one and other people preferring the other, yes. I don't view that as a problem here. I want to reduce friction to making clear APIs.

1 Like

Bear in mind that the .. syntax for optional arguments is "just" default field values - it's not special "optional argument" syntax.

That's the beauty of this specific proposal - there's very little that's special-cased because it's a function call, and what special cases there are about removing boilerplate that passing and destructuring a struct as an argument brings in.

To put that concretely,

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

crop(&img, width: 200, ..);

is a stack of sugar for:

struct CropParameters {
    width: u32,
    height: Option<u32> = None,
    x: u32 = 0,
    y: u32 = 0,
}

fn crop(
    img: &Image;
    CropParameters {
        width,
        height,
        x,
        y,
    }: CropParameters
} -> Image {
    …
}
crop(&img, CropParameters { width: 200, .. });

The only thing that's truly new about this syntax is the ability for the struct to be unnamed and unnameable.

This looks new to me. Or is this just a shortcut for #[derive(Default)] and #[default = …] attributes? The latter of which might not exist either given that it's only documented to specify the default variant for enums.

Please actually at least read the first paragraph of the post. It mentions the merged RFC 3681.

2 Likes

Oh neat, I missed that one. Thanks!

About the example with std::fs::copy, an idea would be to differentiate types for an InPath and OutPath then it would be an explicit compile error to write copy(b, a) if b is an OutPath

You could do that, I think, by:

type OutPath = Path;
type InPath = Path;
fn copy(from: InPath, to: OutPath);

let a = &InPath::new("/some/dir/some/file");
let b = &OutPath::new("/other/file");

// copy(b, a) // Error: invalid type
copy(a, b)

(not testing now, but should work like that?)

This kinda goes off track of an annonymous struct, sorry.
But I feel that "anonymous struct" is kinda a "nuke solution"
But I refrain from opinionating atm

Actually, InPath and OutPath are a flimsy solution, but am just proposing alternatives


edit:
Also, in that example with copy, one could write both ways

copy(_ { from: a, to: b })?;
// and
copy(_ { to: b, from: a })?;

which may introduce mess

What you're describing is the New Type Idiom, which would require struct OutPath(Path) to declare a new type. Your InPath and OutPath are interchangeable still.

Yes, newtypes can absolutely allow an API designer to avoid ambiguity as well, but the caller now has to do some wrapping to call it. You could argue that the anonymous struct is a form of wrapping too I suppose, but it's less boilerplate and fewer needed public items to manage.

I really don't understand some people's issue with reorderable fields of structs, but I've heard this before. :man_shrugging:

4 Likes

This is 100% by design for anything nominal, IMHO. Just like you can construct or destruct a struct in whichever order you like best.

Also, you'll notice that pointers now have copy_to and copy_from methods, so I don't think that "must strictly be done in one prescribed order" really fits with how Rust tends to work overall.

3 Likes

I stand corrected about the new type idioms and their usage in APIs

Order in structs creation / destructuring is what I would like to have, how to say it, more control of? just to have "nicely aligned code" or something I can't express. Maybe more lints for that, but not sure.

imagine:

copy(_ { from: a, to: b })
copy(_ { from: c, to: d })
...
copy(_ { to: f, from: e })

irks a bit, but that's just my whining atp

I'm getting a very strong C++ vine from this, especially from () and {} initializers :sweat_smile:

This is generally the kind of thing that we'd definitely do with a lint not with a hard error, yes. (Without saying whether this specific case should be linted.)

My personal heuristic is that if it'd be harder to write the rejection rule into the spec than to just define what it "obviously" does, then it should be at most a lint. And that's clearly the case for the struct initializers: what it's spec'd to do is obvious no matter the order of field names.

Maybe there's a case for a lint about local inconsistency, but also locally there's presumably a reason that the person put them in the order they did. If it's not more likely that it was accidental than intentional, linting might not be worth doing either.

2 Likes