连接字符串时,需要分配内存来存储结果.最简单的开始是String
和&str
:
fn main() {
let mut owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";
owned_string.push_str(borrowed_string);
println!("{}", owned_string);
}
在这里,我们拥有一个可以变异的字符串.这是有效的,因为它可能允许我们重用内存分配.String
和String
也有类似的情况,比如&String
can be dereferenced as &str
.
fn main() {
let mut owned_string: String = "hello ".to_owned();
let another_owned_string: String = "world".to_owned();
owned_string.push_str(&another_owned_string);
println!("{}", owned_string);
}
在此之后,another_owned_string
保持不变(注意mut
限定符).还有另一个变体consumes和String
相同,但不要求它是可变的.这是一个implementation of the Add
trait,以String
为左侧,&str
为右侧:
fn main() {
let owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";
let new_owned_string = owned_string + borrowed_string;
println!("{}", new_owned_string);
}
请注意,拨打+
后,owned_string
将不再可用.
如果我们想制作一个新的字符串,让两者都保持不变呢?最简单的方法是使用format!
:
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);
}
请注意,这两个输入变量都是不可变的,因此我们知道它们不会被触碰.如果我们想对String
的任意组合做同样的事情,我们可以利用String
也可以格式化的事实:
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!
.您可以 Select clone one string并将另一个字符串附加到新字符串:
fn main() {
let owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";
let together = owned_string.clone() + borrowed_string;
println!("{}", together);
}
Note-我所做的所有类型规范都是多余的-编译器可以推断出这里使用的所有类型.我添加这些问题只是为了让新Rust 的人明白,因为我希望这个问题会受到该群体的欢迎!