Use the format!
macro:
fn hello_world(name: Option<&str>) -> String {
match name {
Some(n) => format!("Hello, World {n}"),
None => format!("Who are you?"),
}
}
In Rust, formatting strings uses the macro system because the format arguments are typechecked at compile time, which is implemented through a procedural macro.
There are other issues with your code:
- You don’t specify what to do for a
None
– you can’t just “fail” to return a value. - The syntax for
if
is incorrect, you wantif let
to pattern match. - Stylistically, you want to use implicit returns when it’s at the end of the block.
- In many (but not all) cases, you want to accept a
&str
instead of aString
.
See also: