[英]How to create a formatted String out of a literal in Rust?
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!
使用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 .在 Rust 中,格式化字符串使用宏系统,因为格式参数在编译时进行类型检查,这是通过过程宏实现的。
There are other issues with your code:您的代码还有其他问题:
None
- you can't just "fail" to return a value.您没有指定要为None
做什么 - 您不能只是“失败”返回一个值。if
is incorrect, you want if let
to pattern match. if
的语法不正确,您希望if let
进行模式匹配。&str
instead of a String
.在许多(但不是全部)情况下,您希望接受&str
而不是String
。See also:也可以看看:
Since Rust 1.58 it's possible to use named parameters , too.从Rust 1.58开始,也可以使用命名参数。
fn hello_world(name: Option<&str>) -> String {
match name {
Some(n) => format!("Hello, World {n}"),
None => format!("Who are you?"),
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.