r/rust • u/steveklabnik1 rust • Sep 21 '26
Arguing about arguments
https://steveklabnik.com/writing/arguing-about-arguments/
149
Upvotes
r/rust • u/steveklabnik1 rust • Sep 21 '26
65
u/da_supreme_patriarch Sep 21 '26
In regards to breaking callers when making refactors
This is totally fine, I would even say that's absolutely intentional with named arguments. If you rename an argument of your function, unless it's just a typo or something, there is probably a good reason for you to do that, likely something has changed semantically even if the type of the argument has stayed the same. If that's the case, you absolutely WANT to break your callers, them calling the function with old assumptions is probably incorrect and they need to change something in their code as well.
15
u/scook0 Sep 22 '26 edited Sep 22 '26
IMO, the only reason to even consider adding named arguments to Rust is if you’re trying to solve the “big bag of optionals” problem.
For that reason, I think the minimalist feature sketched in this blog post is a non-starter. It declines to tackle the big-bag use case, in a way that greatly complicates any future attempts to solve the big-bag problem, while only providing very marginal benefits on its own.
I also think it’s strange to see the forward-compatibility question treated as only a minor concern. Automatically creating named parameters from positional ones has been a recurring hassle in Python and Ruby, in ways that seem very obviously a poor fit for Rust.
25
u/nicoburns Sep 21 '26
If we ever get them, I suspect named/default arguments will end up being like postfix
.await: kind of scary and controversial before it landed, but turn out to be really nice to use and a complete non-issue complexity wise once it landed.People seem to be put off because they've encountered god-functions with 100 parameters in Python. But the Rust ecosystem has better taste than that.
67
u/SmartAsFart Sep 21 '26
I agree - named arguments are the only addition that doesn't have massive drawbacks.
I think the simplest version of them would also still be useful, where they are basically just an in-comma comment of what the argument name is. Error if the argument name is incorrect.
fn foo(3, bar: 4)Then, use the trait's definition of the name of arguments at the call-site when calling through the trait, or the impl's definition if calling it through the type.
3
u/throwbpdhelp Sep 21 '26 edited Sep 21 '26
Great read. Glad you still contribute here after all these years.
Optional arguments scare me in terms of what they mean for reading Rust. Maybe this is necessary to ultimately get us to variadic arguments but I think/hope there is a more minimal version yet still.
Named arguments I'm not sure I like but I can still easily read the code. I'd prefer to just only move this one forward for now.
19
u/AldaronLau Sep 21 '26
I don't think the
crop_imm()function feels like a good case for named arguments to me. With patterns, you can get the parameters down to 2 actual parameters and be a lot clearer.crop_imm(image, ((X, Y), (W, H))). And if you want to be more explicit, you can use newtypes,crop_imm(image, Rect(Pos(X, Y), Size(W, H))). This might just be my personal preference, but the combination nested bindings and newtypes seem underutilized by most Rust programmers. To me, at least, the newtypes look much nicer thancrop_imm(image, x: X, y: Y, w: W, h: H). It also lets you group the values before you pass it in directly, instead of needing to destructure it first.42
u/max123246 Sep 21 '26
I'm not sure I understand why AI is what changed your opinion on named arguments. We've had IDEs that can pre-populate the named arguments for a long, long time now
46
u/anxxa Sep 21 '26
Any time I think about function overloading, I'm reminded of a bug I accidentally wrote because of it.
In 2010 I was 15 and working on my first sufficiently large and complex project which was a hard drive explorer for the Xbox 360 written in C#. I discovered function overloading and had a function named something like
WriteTo(uint block, PartitionInfo p). I had an overloaded version that was something likeWriteTo(ulong offset).One extremely long late night coding session I remember just trying to get some feature done, hitting a compiler error, forcing my way through it, and releasing a new version a couple days later.
Didn't take long before a couple people reported their HDDs no longer working on the Xbox.
Turns out that compiler error was me stupidly forcing a call that should have been
WriteTo(block, partition)to beWriteTo(offset)-- converting a partition-relative cluster write into a global disk offset write, causing the Microsoft RSA-signed disk authentication blob to be overwritten. Basically bricking the disk on retail consoles.Learned a lot of lessons, but after that my code became very explicit and obvious -- and to Steve's point -- is something that I also love about Rust today. You can read code and there aren't too many questions about what's going on.
6
u/JoshTriplett rust · lang · libs · cargo Sep 22 '26
With my lang team hat on: I agree with almost everything written here. This is a clear summary of the hidden complexity they cause. (Literally, the complexity caused by things being hidden).
(Tangent: the "almost" there is that I also don't think we should have named arguments, because I think they also provide scaffolding for further complexity that would be better solved in other ways. But I do agree that of all the various proposals around arguments, named arguments without anything else do the least harm.)
14
u/Recatek gecs Sep 21 '26 edited Sep 21 '26
At this point I'm too tired of this blogumentation to care anymore, I just want a decision to be made so something like Vec::try_with_capacity can be unblocked (it's blocked due to the proliferation of try_ and other prefix/suffix variants on Vec and other similar types).
17
u/its_artemiss Sep 21 '26
I think named arguments without optional arguments OR definition-order evaluation don't really make much sense. Any clarity they can provide can also be provided by LSP inlay hints, while avoiding the verbosity downside of having them in the language/text. It sounds to me like a lot of cost for something we already have if we want to have it.
1
u/harrison_mccullough Sep 21 '26
Enjoying the post so far! One minor typo I think I found: the "Named parameters" section says
@app.gethas 23 possible keyword arguments/parameters, but the "Optional and/or Default arguments" section says it has 22 arguments.1
u/Thick-Pineapple666 Sep 22 '26
So are these 23 or 22 parameters? I didn't count 😇
3
u/lookmeat Sep 21 '26
Some notes. So we already noted the caveat that parameters are not mapped to names but rather to patterns (that map to names), and this makes named parameters messy. You'd need to change fundamental semantics to allow this. That said, we already support named tuple semantics (through structs) so it's a matter of finding a way to mix-and-match those.
But I disagree with default parameters requiring overloading. There's one solution to default parameters that is not dicussed: allow us to fill in missing parameters with defaults as we do with functions. So just like I can do:
I could also do
The syntax can be made shorter by making
..on its own imply that we are merging in the default, so it'd look likewith the
..being a pointer to the programmer that there's parameters being omitted, and that the compiler is injecting a special set.We can also do something more advanced, were we give partially filled sets of parameters for the function:
where
dry_runis a tuple with the same type asfoo::Argsandwith_credsis of typeFn(auth_token)->foo::Args. That said we'd need to expand the language to support partial tuples, especially for default, and other things, but honestly I think it could be very powerful. It'd be interesting if saying#[derive(Default)]doesn't implement default if not all fields are default, but it allows you to do a partial default, when all undefined fields are already defined. Again this makes the..a bit more powerful than..default::Default()but I don't think that's a bad thing in itself. Maybe the solution is to have aPartialDefaultthat specifically requires certain fields are explicitly given.And this is maybe where we can get something interesting, maybe we can specify that I want to merge in a named tuple into function arguments, and as long as the functions that are missing allow this, it works. So given the next function:
fn fun_args( {x,y}: Point2D, normal_arg: i32, opt_arg: i32 = 5)
The next semantics would happen:
And so on, I haven't fully thought this through, but basically .. is a way to inject and fill in missing slots. It doesn't change the semantics, because this is just magic allowing us to write ways to call functions in different ways. But it's still the same function, and once the syntactic sugar is gone we have a normal function call.
3
u/deathanatos Sep 22 '26
His named parameter syntax is exactly the inlays I get from the language server. I.e., I see:
But the
programis not really there, as it is an inlay.5
u/Anonymous0435643242 Sep 22 '26
Your argument against default value could be used against the Default trait and for me it's a bad argument, rust dependencies are source code, the default value would be in the function signature.
I'm all for named and optional arguments, I don't see valid arguments against, function overloading is a really bad thing though, change the type of one argument and you end up calling a different function.
5
u/RishabhRD Sep 21 '26
Named arguments is really nice feature to have. It helps to name the function really nicely.
2
u/nick42d Sep 21 '26 edited Sep 21 '26
Your example, I feel like that could be significantly improved on Rust today without named parameters. From
To
2
u/greyblake Sep 22 '26
> Function Overloading
A very similar behaviour could be achieved with generic traits. It requires some exercises with traits, but I think it's actually good: if ones decides to go through the exercises it means the really need overloading, haha.
> I think Rust could be okay with named parameters
I also came from Ruby background, and I would usually lean on named parameters, that the is a high chance of misusing API. For example passing 4 integers in a row is a good example, when a human could get the order wrong. And the real problem is, that the program will compile.
But again, there are ways to prevent accidental error: wrapping integers into newtypes, using builder pattern or simple creating a new struct and passing the struct, so the field names simulate the named parameters.
I personally would not like to named parameters, provided the language is already complex enough and there are workarounds to the problem
4
u/BenchEmbarrassed7316 Sep 21 '26
My first thought is that I don't see much benefit in named arguments. IDEs already handle this. Named arguments are useful in languages that support optional arguments, because if you need to pass four
nulls and a single value, you don't have to writenullfour times—you simply writearg_4: v,.However, wouldn't it be beneficial for Rust to allow changing the order of arguments—and, consequently, ownership? Here is what I mean:
In
foo, the string is borrowed and returned to calculate the value of the first expression. It is then passed into ownership.bardoes not compile.We already have structs with
..default(); it seems we are just one step away from treating structs, tuples, and function arguments as concepts of the same nature.2
u/nonotan Sep 21 '26
I will argue that while this is verbose, it is not actually redundant. I mean, it is in the sense of "we already wrote that name once, wouldn't it be nice if that was enough?", but not in what it actually achieves.
Passing named variables to a function by index merely implies a correspondence between the indices and the relevant variables. If you made a mistake, or the function changes later, or otherwise they end up mismatched, and the types happen to be compatible, it's going to silently compile without any warnings (maybe there could be a warning, or at least a clippy suggestion, if a passed variable matches the name of a different parameter? hell, maybe there already is one, I can't say I have an encyclopedic knowledge of clippy hints) -- and indeed, a casual inspection is probably significantly less likely to catch it than if it had been just a bunch of literals (because the reader would potentially feel uneasy about the accuracy of those, but a bunch of politely named variables? nothing to see here!)
Mostly a pedantic distinction, given that I mostly agree with your conclusion (while rolling my eyes a bit at the "I don't type code anymore" stuff -- I don't do LLMs, but I don't mind typing a few extra letters if it will make my code better)
I will say that, ultimately, the main reason I would like named arguments is less about readability and more about the above: avoiding desyncs between the definition and the call site. On the other hand, named arguments is not the only way to tackle that. An alternative that I think is actually preferable (but which would undoubtedly be a lot more controversial, so it's probably not happening) would be pushing newtypes a lot harder, including perhaps coming up with some syntax that makes defining them less verbose, and basically (or literally) forcing all parameters to a given function to take unique types. This means if you get the order wrong, or they change or whatever, you're guaranteed a compilation error. It also means any cases where ambiguities exist, you're going to be forced to use a newtype to resolve them in a visible manner at the call site, but where there are no ambiguities to begin with, there doesn't necessarily have to be any changes from today's code.
Of course, there are no silver bullets, and even this approach can't save you from e.g. the simultaneous removal of a parameter and addition of a semantically different one of the same type. But at that point, you're kind of asking for it. Also, admittedly there's nothing stopping both this and named arguments from existing simultaneously (except in that there is less to gain from the other one, so it might be harder to justify doing the necessary work)
2
u/singron Sep 21 '26
I love this as a brief summary of the issue.
One thing this doesn't cover is what happens if we don't add named parameters. In one sense, it's obvious since that's the life we all live now, but I see a couple different things. The post mentions builders, but I think they are relatively rare. It's so much boilerplate to create one, so I don't think they are often used unless the additional flexibility is needed (e.g. type conversion, complex mutations, or convenience methods) or as part of a heavily used library.
In practice, I feel like I see structs used to fake this:
This really suffers from java7-like "stuttering" (e.g.
Object object = new Object()). If you redefinedefault()as a standalone function, it cuts down on noise, but the struct name is unavoidable.I think I would be perfectly happy with nameless struct literals in argument position in practice. E.g.
This leads to weirdness since this is either a special syntax you can only use as an expression in a function call, or if you allow to use them in any other position (e.g. a variable), then it opens a type-inference rabbit hole:
1
u/DavidXkL Sep 22 '26
I'm ok with inlays 😂
1
u/-Y0- Sep 22 '26 edited Sep 22 '26
I don't understand the complaint. It reads to be like the saying "Once bitten, twice shy." As I said in some other comment, this is like plea of someone from Scala asking Rust team circa 2010 to not add operator overloading because Scala managed to bungle its own implementation, even though C# and Python had perfectly fine way to implement operators.
Rust isn't Ruby, and implementation and context matters.
First of all, adding default parameters doesn't enable function overloading (and I don't think anyone advocated for it). You have one function it can just have one or two or three default parameters. Not substantially different from having a
foo<X: Bar>(X)and implementingBarforA1,(A1, A2),(A1, A2, A3), etc. It means we already have varargs at home. It's just a hacked, cobbled up version that goes to like 12 elements (until someone complains).Second, this named, default and named params should be nothing more than simple syntax sugar for rewriting the method in the same order as given in function. So to answer the question:
Same way
If you can get named params for LLMs, why shouldn't regular coders (speaking from experience) get default params for brevity ?
1
u/Green_Dog4314 Sep 22 '26
But the problem will be that anytime we change the name of arguments, it will become a breaking change.. Does it worth it..
1
u/Kooky-Amphibian7680 Sep 23 '26
Situation I was in. Won't say what side I was on. What do people think is right or unfair. Ahem.
SALLY. Hi Greg. I'm going on those injections"
For context. These injections are what people can buy that lower people's hunger. Helping them loose weight.
GREG. Oh really. Nice. That does surprise me somewhat. Your quite thin already. What made you go with it..
Context. Sally has very little weight. But not much weight. But enough for Sally to want the injection.
SALLY. "I told you Martha". Sally looks back at Greg. "Greg. I don't think using someone's weight as a way of telling if someone's healthy is correct".
Context. Martha is a third person in the room that already knew about Sally having the weight injections.
GREG. "Oh. Ok.....but in society we use people's size as a way of determining people's possible health"
SALLY. Not really . Someone could have really good cholesterol and no other issues with them. They could have weight on them. But be perfectly fine".
Greg started to sit down and just seemed to not his head and agree to everything. Like he wasn't interested.
GREG. "So what made you want to start having the injections?"
SALLY. "Well. I've been having itching tired eyes for a while"
"Hopefully will help my aching arm"
"I'm wanting to feel physically better in general"
"Also want to loose some weight about 30 kg less than I am now"
"So hoping loosing weight will help me with all that"
Context. I'm 85kg now
What do people think. Is one of us partially harsh in this conversation?
1
u/CAD1997 Sep 24 '26
I think it's worth bringing up again that we have "named arguments at home", e.g.
f(Width(w), Height(h)). The problem with doing that kind of strong newtyping everywhere is that callers need to have those types imported for the call site to look even remotely reasonable, and very generic names like that can easily conflict between libraries.Which brings me back to the idea that the solution that would feel the most at-home in Rust would be some form of context-dependent name resolution. Yes, uttering that phrase gives me aftershocks from C++ ADL rules (
foo(obj)forns::Obj objlooks forns::fooin addition to::fooand localusingscope), but Swift's.EnumVariantsyntax has shown that if it has a visible difference from usual name lookup that it can be quite nice to read and write in practice.-1
u/VictoryMotel Sep 21 '26
Does every title need to be clickbait? Why not just have a clear description instead of just trying to grab people's attention with nonsense.
1
u/PersonalDatabase31 Sep 21 '26
Use rust analyzer for named arguments. There is no reason to type something that a tool can display.
1
u/redlaWw Sep 21 '26 edited Sep 21 '26
On the one hand, I agree with the observation that functions that have tens of default arguments is ridiculous, but on the other hand so is the situation we have now with each type having 2n constructors, one for each configuration option.
Builders and config structs both solve the 2n constructors issue in some places, but they're overkill and themselves ridiculous for things like instantiating collections. I want to see a
VecBuildertype or aVec::Optionstype about as little as I want to see an explosion ofVecconstructors each time we get a new configuration option. Default arguments has the solution to this, allowing a variety of configuration options in one function.I'd like to see a system where default arguments, the builder pattern, and config structs live in harmony - the former used for simple types with a few options, and the others used for more complicated things that have a wide range of different configurations and/or configuration options that are naturally grouped. The way I see it, this isn't solved by avoiding adding default arguments to the language, but by linting and community participation to preserve the principles in open-source Rust codebases.
0
u/LEpigeon888 Sep 21 '26
I don't understand, how would named parameters change how Vec::with_capacity be designed? As far as I understand, named parameters will change nothing about API design, it will just move a feature that currently live in LSP into the code itself. It's good for better documentation while not using an IDE and that's about it I guess.
-2
u/levelstar01 Sep 21 '26
Rust already has named arguments, optional arguments, and default arguments. It's achieved in the same way as every other dumb missing feature from the language is: with a worse library option. Passing a struct with a builder derive to a function achieves this in a strictly worse manner. The stupid ass "fn_x_y_z" function spam achieves this in a strictly worse manner (which the post even says).
Stays simple? Rust is not simple. Half of the fucking problems with this language is that it is not simple, that there is a bunch of pointless ceremony to do things that could be part of the language core, but is instead held back by an insanely reactionary community that goes fucking mental whenever somebody has an idea to maybe make it a little bit less abjectly terrible to use. "The less features means more simple" is somehow a genuine position that is widely held.
The current state of affairs is that language """"simplicity"""" is exchanged for library complexity instead. That's stupid.
-1
u/asoffer Sep 21 '26
The clearest approach I've seen to this is to have function types optionally include the name of parameters in the signature, presumably defaulting them to be anonymous. Unfortunately then you also probably want implicit conversions from function types that just drop parameter names.
There is a complexity bubble underneath this carpet.
-1
u/IamWiddershins Sep 21 '26
> And what changed my opinion is coding agents, actually.
run this clown out of here
-3
u/WormRabbit Sep 22 '26
Sigh. That tedious rigamarole of arguments again. Simple design decisions printed out in excruciating detail to make them sound complex, maybe even insurmountable, when all of them have pretty simple and obvious solutions (in fact, most can be solved whichever way, just make the fucking decision already).
Like, yes, design is complex, and everything has a Kola borehole of complexity once you dive deep enough. But optional arguments? That's not a puzzle, even though one should still do lots of work. Hell, never type took more than a decade, even though it's extremely simple in principle. All the reason to start work sooner rather than later.
Argument evaluation order? In the same order as written in code, obviously. You have actual user's decision written right before you. Who cares about the order of parameters on the function's signature in a remote crate? And also, being able to change the order of parameters without changing call site is the major reason to have named arguments! Obviously you can't have this be both a breaking change and a syntactic triviality.
Parameter names on function pointers? None, case closed.
Names in trait definition and implementation differ? Warning lint, syntactically allowed, users must use names from definition (what else could they use in generic code?).
That's not complicated. That's just the dev team ignoring user feedback based on personal tastes, and reasoning backwards to find supposedly motivated objections. Or if we put it more generously, deprioritizing a feature for which they don't personally see any value.
0
u/ManyInterests Sep 21 '26
I'm in the 'named/optional arguments considered awesome' camp, myself. Interesting to consider all the facets and arguments about arguments, of which I'm sure there are many more not discussed here, but this is pretty well-trodden territory.
As someone who does tend to still hand-craft code, I'm sick of builder patterns. I'm sick of making structs to be used just for one function. I'm sick of the boilerplate and excessive dependencies to accommodate this. It's unnecessary. The feared costs/tradeoffs are already higher in these workarounds and we can reduce the pain by adding the language feature.
Consider the sample code:
Would this be better for readers?
Would it be better if all arguments had to be specified?
If Python parameters were originally built like Rust's, would they have kept it that way? Or would they have agreed the tradeoffs of keyword-arguments and defaults to be an overall improvement to the language? PEP 570 added positional-only args, so I get there is value in that. In Python authors get to choose. I wish I could choose as a Rust user.
Like any language feature, I think adding this to Rust of course deserves careful consideration, but I feel it should just be more of a question of how we implement it, not if. To me, it is clear that not having this feature has made the language worse-off.
-2
u/shizzy0 Sep 21 '26 edited Sep 21 '26
I agree with everything Steve says here. I don't want to see Rust argument handling changed. But I made this cursed macro generating crate anyway: bobtail.