rust - 在 Rust 中使用字符串文字进行更方便的连接

标签 rust

在 nightly Rust 中,不再可能将字符串文字指定为 String with a "~" character .

例如,在 C++ 中,我使用 user-defined literals连接字符串文字而无需每次都提及 std::string 的外壳:

inline std::string operator"" _s (const char* str, size_t size) {return std::string (str, size);}
foo ("Hello, "_s + "world!");

Rust 中是否存在或计划使用类似的功能来使字符串文字连接比 String::from_str ("Hello, ") + "world!" 更轻松?

最佳答案

如果你从字面上(哈)有字符串文字,你可以使用 concat!宏观:

let lit = concat!("Hello, ", "world!")

您可以原生地将字符串拆分为多行:

let lit = "Hello, \
           World";

\ 消耗所有后续空白,包括下一行的前导空格;省略 \ 将“逐字”包含字符串数据,以及换行符和前导空格等。

您可以将 &str 添加到 String:

let s = "foo".to_string() + "bar" + "baz";

你可以使用 push_str迭代地:

let mut s = "foo".to_string();
s.push_str("bar");
s.push_str("baz");

你可以使用 SliceConcatExt::concat :

let s = ["foo", "bar", "baz"].concat();

如果一切都失败了,你可以定义一个宏来做你想做的事。

另见:

关于rust - 在 Rust 中使用字符串文字进行更方便的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25328310/

相关文章:

shell - fzf,stdin出现问题,并从rust :调用程序

enums - 如何根据当前枚举值选择一个有限制的随机枚举值?

rust - 为 Iterator::find 提供闭包时的值和引用

performance - Rust 在解析文件时比 Python 慢

postgresql - 不满足特征绑定(bind) `chrono::DateTime<Utc>: FromSql<diesel::sql_types::Nullable<diesel::sql_types::Timestamptz>, Pg>`

rust - 是否可以有条件地启用 `derive` 之类的属性?

rust - 如何检查 NEAR 账户是否部署了智能合约并实现了所需的接口(interface)?

rust - 在不安全的 rust 中通过 *mut T 来突变 &T 是 UB 吗?

arrays - 访问嵌套数组中的值

pointers - 指向 Result<Vec<f64>, _> 中向量第一个元素的指针已损坏