Feature request: optional arguments/struct fields etc

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:

(this is talking about named arguments, but many of the links talk about default arguments, i.e. optional arguments, as well)

4 Likes

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