看板 Marginalman 關於我們 聯絡資訊
: https://space.bilibili.com/361469957/lists/3902595 : 從入門到入門 1. 肥胖的 &str &str 一般被認為是字串切片,但指標的部分他比 String 還要大 因為他除了指向 heap 的指標還要帶有切片大小 (len) 資訊 這種 Slice 類型的指標也被稱為肥指標 (Fat Pointer) 而且 &str 的索引必須在 UTF-8 的字串上 不是會出錯並 crash 2. &str 的借用 &str 也是一種借用 借用週期與普通借用一樣 從第一次借用到最後一次借用 而且 &str 的借用一樣會讓 String 失去寫入的權限 3. let s = "Here, the World" 上面這段描述的 s 並不是借用 而是指向一個字串常數 (String Literal) 的靜態引用 (static reference) 因此他是 &'static str 當這樣寫 let mut s = "Here, the World" 這時候是個小陷阱 這邊的 mut 意思是 s 可變而不是後面 "Here, the World" 本身是不可變常數 你能做的 mut 是重新賦予 s 新的數值 問題:誰比較大 fn main() { let s = String::from("Here, the World"); let s2: &String = &s; let s3: &str = &s[..]; } 因為 &str 是肥指標所以 s3 比 s2 占用的字節數還多 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.248.143.172 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1744943681.A.308.html