迷途參照
我們現在可以瞭解 Rust 中有兩種字串型別,&str 幾近於 &[char],但其資料是以可變長度編碼 (UTF-8) 儲存。
fn main() { let s1: &str = "World"; println!("s1: {s1}"); let mut s2: String = String::from("Hello "); println!("s2: {s2}"); s2.push_str(s1); println!("s2: {s2}"); let s3: &str = &s2[6..]; println!("s3: {s3}"); }
以 Rust 術語來說會是這樣:
&str是對字串切片的不可變參照。String是可變動的字串緩衝區。
-
&strintroduces a string slice, which is an immutable reference to UTF-8 encoded string data stored in a block of memory. String literals (”Hello”), are stored in the program’s binary. -
Rust 的
String型別是位元組向量的包裝函式。就像使用Vec<T>一樣,該型別有專屬的擁有者。 -
As with many other types
String::from()creates a string from a string literal;String::new()creates a new empty string, to which string data can be added using thepush()andpush_str()methods. -
The
format!()macro is a convenient way to generate an owned string from dynamic values. It accepts the same format specification asprintln!(). -
您可以透過
&str和可選的範圍選項,從String借用&str切片。如果所選位元組範圍未與字元邊界對齊,運算式會發生恐慌。比起嘗試設定正確的字元邊界,建議優先使用會對字元進行疊代的chars疊代器。 -
For C++ programmers: think of
&strasstd::string_viewfrom C++, but the one that always points to a valid string in memory. RustStringis a rough equivalent ofstd::stringfrom C++ (main difference: it can only contain UTF-8 encoded bytes and will never use a small-string optimization). -
Byte strings literals allow you to create a
&[u8]value directly:fn main() { println!("{:?}", b"abc"); println!("{:?}", &[97, 98, 99]); }