fn main() {
let borrowed_string: &str = "hello ";
let another_borrowed_string: &str = "world";
let together = format!("{}{}", borrowed_string, another_borrowed_string);
// After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
// let together = format!("{borrowed_string}{another_borrowed_string}");
println!("{}", together);
}
fn main() {
let owned_string: String = "hello ".to_owned();
let another_owned_string: String = "world".to_owned();
let together = format!("{}{}", owned_string, another_owned_string);
// After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
// let together = format!("{owned_string}{another_owned_string}");
println!("{}", together);
}
不过,你并不一定要使用format!,你可以克隆一个字符串,然后将另一个字符串追加到新字符串中:
fn main() {
let owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";
let together = owned_string.clone() + borrowed_string;
println!("{}", together);
}
从Rust 1.58开始,您还可以连接两个或更多变量,如下所示:format!("{a}{b}{c}")。它基本上与format!("{}{}{}", a, b, c)相同,但更短一些,(可以说)更容易阅读。这些变量可以是String、&str(也可以是其他非字符串类型)。结果是String。更多信息请参见this。
9条答案
按热度按时间nhaq1z211#
连接字符串时,需要分配内存来存储结果,最简单的方法是从
String
和&str
开始:这里,我们有一个我们可以改变的拥有的字符串。这是有效的,因为它潜在地允许我们重用内存分配。对于
String
和String
也有类似的情况,因为&String
可以被解引用为&str
。在这之后,
another_owned_string
就不再被使用了(注意没有mut
限定符)。还有一个变体,它 * 消耗 *String
,但不要求它是可变的。这是Add
特征的一个实现,它把String
作为左边,把&str
作为右边:请注意,在呼叫
+
之后,就无法再存取owned_string
。如果我们想生成一个新的字符串,而不去修改这两个字符串,那该怎么办呢?最简单的方法是使用
format!
:注意,两个输入变量都是不可变的,所以我们知道它们是不可修改的。如果我们想对
String
的任何组合做同样的事情,我们可以利用String
也可以被格式化的事实:不过,你并不一定要使用
format!
,你可以克隆一个字符串,然后将另一个字符串追加到新字符串中:注意-我做的所有类型规范都是多余的-编译器可以推断出这里使用的所有类型。我添加它们只是为了让Rust的新手清楚,因为我希望这个问题在那个组中很受欢迎!
oalqel3c2#
要将多个字符串连接成一个字符串,并用另一个字符分隔,有几种方法。
我见过的最好的方法是在数组上使用
join
方法:根据您的使用情形,您可能还希望获得更多控制:
还有一些我见过的手动方法,有些避免了一个或两个分配在这里和那里。为了可读性的目的,我发现以上两个是足够的。
pdsfdshx3#
在Rust中连接字符串的简单方法
Rust中有多种方法可用于连接字符串
第一种方法(使用
concat!()
):上面代码的输出是:
AB公司
第二种方法(使用
push_str()
和+
运算符):上面代码的输出是:
AB公司
abc公司
第三种方法(
Using format!()
):上面代码的输出是:
AB公司
请查看并试用Rust playground。
tyg4sfes4#
我认为这里还应该提到
concat
方法和+
:还有
concat!
宏,但仅用于文字:at0kjp5o5#
通过字符串插值进行连接
更新:自2021年12月28日起,Rust 1.58测试版中提供了这个功能。你不再需要Rust Nightly build来做字符串插值。(答案的其余部分保持不变)。
2019年10月27日发布的RFC 2795:建议支持隐式参数来执行许多人所知道的“字符串插值”--一种在字符串中嵌入参数以连接它们的方法。
RFC:https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
最新的问题状态可在此处找到:https://github.com/rust-lang/rust/issues/67984
在写这篇文章的时候(2020-9-24),我相信这个功能应该可以在Rust Nightly构建中使用。
这将允许您通过以下简写进行连接:
它相当于:
还有一个“ifmt”框,它提供了自己的字符串插值:
https://crates.io/crates/ifmt
bybem2ql6#
从Rust 1.58开始,您还可以连接两个或更多变量,如下所示:
format!("{a}{b}{c}")
。它基本上与format!("{}{}{}", a, b, c)
相同,但更短一些,(可以说)更容易阅读。这些变量可以是String
、&str
(也可以是其他非字符串类型)。结果是String
。更多信息请参见this。kcugc4gi7#
串联两个
String
:串联两个
&str
:a1o7rhls8#
默认情况下,Rust中的所有内容都是关于MemoryManage、Owenership和Move的,我们通常不会看到类似复制或深度复制的内容,因此 * 如果您尝试连接字符串,则左手应键入String,它是可增长的,并且应为可变类型,右侧可以是普通字符串文字,也就是String切片类型 *
来自文档的官方声明,这是指当您尝试使用arthmatic +运算符时
am46iovg9#