在每晚的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();
如果所有其他方法都失败了,您可以定义一个宏来完全按照您的意愿行事。
也可以看看: