连接字符串时,需要分配内存来存储结果。最容易上手的是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 限定符)。还有另一个变体使用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!。您可以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);
}
注意 - 我所做的所有类型规范都是多余的 - 编译器可以在这里推断出所有类型。我添加它们只是为了让刚接触 Rust 的人清楚,因为我希望这个问题会受到该群体的欢迎!