I'm about to return a string depending the given argument.
fn hello_world(name:Option<String>) -> String {
if Some(name) {
return String::formatted("Hello, World {}", name);
}
}
This is a not available associated function! - I wanted to make clear what I want to do. I browsed the doc already but couldn't find any string builder functions or something like that.
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:
None
- you can't just "fail" to return a value.if
is incorrect, you want if let
to pattern match.&str
instead of a String
.See also:
Since Rust 1.58 it's possible to use named parameters, too.
fn hello_world(name: Option<&str>) -> String {
match name {
Some(n) => format!("Hello, World {n}"),
None => format!("Who are you?"),
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With