简体   繁体   English

如何从 Rust 中的文字创建格式化字符串?

[英]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:您的代码还有其他问题:

  1. You don't specify what to do for a None - you can't just "fail" to return a value.您没有指定要为None做什么 - 您不能只是“失败”返回一个值。
  2. The syntax for if is incorrect, you want if let to pattern match. if的语法不正确,您希望if let进行模式匹配。
  3. Stylistically, you want to use implicit returns when it's at the end of the block.从风格上讲,您希望在块的末尾使用隐式返回。
  4. In many (but not all) cases, you want to accept a &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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM