基本字符串操作
fn main() {
// Statically allocated string slice
let hello = "Hello world";
// This is equivalent to the previous one
let hello_again: &'static str = "Hello world";
// An empty String
let mut string = String::new();
// An empty String with a pre-allocated initial buffer
let mut capacity = String::with_capacity(10);
// Add a string slice to a String
string.push_str("foo");
// From a string slice to a String
// Note: Prior to Rust 1.9.0 the to_owned method was faster
// than to_string. Nowadays, they are equivalent.
let bar = "foo".to_owned();
let qux = "foo".to_string();
// The String::from method is another way to convert a
// string slice to an owned String.
let baz = String::from("foo");
// Coerce a String into &str with &
let baz: &str = &bar;
}
注意: String::new
和 String::with_capacity
方法都将创建空字符串。但是,后者分配初始缓冲区,使其最初变慢,但有助于减少后续分配。如果已知 String 的最终大小,则首选 String::with_capacity
。