Avatar ·

How to implement default function arguments in Rust?

Hello, colleagues! I'm new to Rust and coming from Python, where you can easily write functions with default arguments:

\n\n
def greet(name, greeting="Hello"):\n    print(f"{greeting}, {name}!")
\n\n

Now I'm trying to do the same in Rust, but the compiler complains. Here's my code:

\n\n
fn greet(name: &str, greeting: &str = "Hello") {\n    println!("{}, {}!", greeting, name);\n}
\n\n

The compiler gives an error: expected identifier, found `=`. I understand that Rust doesn't have syntax for default arguments, but how do I solve this problem? I need the function to work with one argument (then the default greeting is "Hello") as well as with two.

\n\n

I've already tried using function overloading, but Rust doesn't support it.