在 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/