如何从 Rust 中的文字创建格式化的字符串? [英] How to create a formatted String out of a literal in Rust?

查看:230
本文介绍了如何从 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.

推荐答案

使用 format!:

fn hello_world(name: Option<&str>) -> String {
    match name {
        Some(n) => format!("Hello, World {}", n),
        None => format!("Who are you?"),
    }
}

在 Rust 中,格式化字符串使用宏系统,因为格式参数在编译时进行类型检查,这是通过一个过程宏实现的.

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:

  1. 您没有指定要为 None 做什么 - 您不能只是失败"返回一个值.
  2. if 的语法不正确,您希望 if let 进行模式匹配.
  3. 在风格上,您希望在块末尾时使用隐式返回.
  4. 许多(但不是全部)情况下,您希望接受 &str 而不是 String.
  1. You don't specify what to do for a None - you can't just "fail" to return a value.
  2. The syntax for if is incorrect, you want if let to pattern match.
  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.

这篇关于如何从 Rust 中的文字创建格式化的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆