楼主:
yam276 ('_')
2025-04-18 10:34:39: 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 占用的字节数还多