如何连接以下类型组合:
str
和str
String
和str
String
和String
连接字符串时,需要分配内存来存储结果。最简单的开始是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);
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);
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的人清楚,因为我希望这个问题能够受到这个群体的欢迎!
要将多个字符串连接成一个字符串,由另一个字符分隔,有几种方法。
我见过最好的是在数组上使用join
方法:
fn main() {
let a = "Hello";
let b = "world";
let result = [a, b].join("\n");
print!("{}", result);
}
根据您的使用情况,您可能还需要更多控制:
fn main() {
let a = "Hello";
let b = "world";
let result = format!("{}\n{}", a, b);
print!("{}", result);
}
我看到了一些更多的手动方式,有些方法可以避免一两次分配。出于可读性目的,我发现上述两个就足够了。