在Rust中使用字符串文字更方便的连接

问题描述 投票:8回答:3

在每晚的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!"更少痛苦?

rust
3个回答
20
投票

如果你真的(哈)有字符串文字,你可以使用concat!宏:

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

您可以在几行中原生地拆分字符串:

let lit = "Hello, \
           World";

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

你可以添加&strString

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();

如果所有其他方法都失败了,您可以定义一个宏来完全按照您的意愿行事。

也可以看看:


13
投票

您可以使用format!宏。它更具可读性,更易于翻译,更高效,更强大(你可以连接不仅仅是字符串,就像C ++的ostringstream一样)。它也是完全类型安全的。

format!("Hello, {}", "world!")

您还可以使用命名参数来提高可读性。

format!("hello, {who}", who = "world")

完整的格式化语法在std::fmt中描述。

Rust没有用户定义的文字。我认为添加这样的功能是向后兼容的,所以也许这个功能将在Rust 1.0之后添加。


1
投票

您可以在不使用strString宏的情况下连接concat!文字:

let input = concat!("Hello", ' ', "world");

要使其成为字符串,请指定目标类型并使用into

let input: String = concat!("Hello", ' ', "world").into();

完整计划:

fn main() {
    let input: String = concat!("Hello", ' ', "world").into();
    println!("{}", input);  // Output: Hello world
}
© www.soinside.com 2019 - 2024. All rights reserved.