我即将根据给定的参数返回一个字符串。
fn hello_world(name:Option<String>) -> String {
if Some(name) {
return String::formatted("Hello, World {}", name);
}
}
这是一个不可用的关联函数! - 我想清楚我想做什么。我已经浏览了文档,但没有找到任何字符串构建函数或类似的东西。
我即将根据给定的参数返回一个字符串。
fn hello_world(name:Option<String>) -> String {
if Some(name) {
return String::formatted("Hello, World {}", name);
}
}
这是一个不可用的关联函数! - 我想清楚我想做什么。我已经浏览了文档,但没有找到任何字符串构建函数或类似的东西。
使用format!
宏:
fn hello_world(name: Option<&str>) -> String {
match name {
Some(n) => format!("Hello, World {n}"),
None => format!("Who are you?"),
}
}
Rust中,格式化字符串使用宏系统,因为格式参数在编译时进行类型检查,这是通过过程宏(procedural macro)实现的。
您的代码还存在其他问题:
None
要执行什么操作——您不能只是“失败”而不返回值。if
的语法是不正确的,您需要使用if let
进行模式匹配。&str
而不是String
。另请参见: