Currently, the best you get for optional arguments is to use an Option, or something like this:
fn maybe_plus_5<T: Into<Option<i32>>>(x: T) -> i32 {
x.into().unwrap_or(0) + 5
}
This works, but it looks pretty messy. My suggestion is to be able to specify optional arguments by adding an =
after the type or the name, like this:
fn hello(name: &str = "world") {
format!("Hello {}!", name)
}
// or
fn hello(name = "world": &str) {
format!("Hello {}!", name)
}
This is a pretty common feature of most languages, and I'm surprised Rust doesn't have this. It would make creating functions, structs etc much easier. Thank you!
2 Likes
This has been discussed at length at least a few times. A quick search turned up this discussion: Named & Default Arguments - A Review, Proposal and Macro Implementation
3 Likes
See also:
There definitely is interest. You assume correctly.
There's 700+ comments to read there, probably more. As for why things haven't been implemented - there's no consensus on how, or even if they should be implemented. That's why I think macro explorations of this are useful.
I like this summary best of how hairy of a topic this is:
(this is talking about named arguments, but many of the links talk about default arguments, i.e. optional arguments, as well)
4 Likes
system
Closed
November 28, 2021, 2:05pm
4
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.