String
String 是標準堆積配置的可成長 UTF-8 字串緩衝區:
fn main() { let mut s1 = String::new(); s1.push_str("Hello"); println!("s1: len = {}, capacity = {}", s1.len(), s1.capacity()); let mut s2 = String::with_capacity(s1.len() + 1); s2.push_str(&s1); s2.push('!'); println!("s2: len = {}, capacity = {}", s2.len(), s2.capacity()); let s3 = String::from("🇨🇭"); println!("s3: len = {}, number of chars = {}", s3.len(), s3.chars().count()); }
String 會實作 Deref<Target = str>。也就是說,您可以在 String 上呼叫所有 str 方法。
This slide should take about 10 minutes.
String::new會傳回新的空白字串,如果您知道要向字串推送多少資料,請使用String::with_capacity。String::len會傳回String的大小 (以位元組為單位,可能與以字元為單位的長度不同)。String::chars會傳回實際字元的疊代器。請注意,由於字形叢集的關係,char和一般人所認為的「字元」可能不同。- 提到字串時,一般人可能是指
&str或String。 - 當型別實作
Deref<Target = T>時,編譯器可讓您以公開透明的方式呼叫T中的方法。- 我們尚未討論
Deref特徵,因此目前主要會講解說明文件中的側欄結構。 String會實作Deref<Target = str>,後者能以公開透明的方式授予前者str方法的存取權。- Write and compare
let s3 = s1.deref();andlet s3 = &*s1;.
- 我們尚未討論
String是以包裝函式的形式在位元組向量的四周實作,許多在向量上支援的作業也適用於String,但需要某些額外保證。- 請比較各種為
String建立索引的方法:- 使用
s3.chars().nth(i).unwrap()變為字元,其中i代表是否出界。 - 使用
s3[0..4]變為子字串,其中該切片會位於字元邊界上,也可能不會。
- 使用
- Many types can be converted to a string with the
to_stringmethod. This trait is automatically implemented for all types that implementDisplay, so anything that can be formatted can also be converted to a string.