在 Rust 中与字符串文字更方便的连接 [英] A more convenient concatenation with a string literal in Rust
问题描述
在夜间 Rust 中,不再可能将字符串文字指定为 String 一个~"字符.
In the nightly Rust it is no longer possible to designate a string literal as String with a "~" character.
例如,在 C++ 中,我使用 用户定义的文字 连接字符串文字,而不必每次都提到 std::string
:
In C++, for example, I'm using user-defined literals to concatenate string literals without the crust of mentioning std::string
every time:
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!"
更少痛苦?
Is there a similar feature existing or planned in Rust to make string literal concatenation less painful than String::from_str ("Hello, ") + "world!"
?
推荐答案
如果你真的(哈哈)有字符串文字,你可以使用 concat!
宏:
If you literally (hah) have string literals, you can use the concat!
macro:
let lit = concat!("Hello, ", "world!")
您可以在本地将字符串拆分为多行:
You can natively split strings over several lines:
let lit = "Hello, \
World";
\
消耗所有后面的空格,包括下一行的前导空格;省略 \
将包括字符串数据逐字",带有换行符和前导空格等.
The \
consumes all following whitespace, including the leading spaces on the next line; omitting the \
will include the string data "verbatim", with newlines and leading spaces etc.
您可以将 &str
添加到 String
:
You can add a &str
to a String
:
let s = "foo".to_string() + "bar" + "baz";
您可以使用 push_str
迭代:
You could use push_str
iteratively:
let mut s = "foo".to_string();
s.push_str("bar");
s.push_str("baz");
你可以使用 SliceConcatExt::concat
:
You could use SliceConcatExt::concat
:
let s = ["foo", "bar", "baz"].concat();
如果一切都失败了,你可以定义一个宏来做你想做的事.
If all else fails, you can define a macro to do exactly what you want.
另见:
这篇关于在 Rust 中与字符串文字更方便的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!