Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

ch04b 引用与借用

对应原书:ch04-02 引用与借用 · ch04-03 Slice 类型

上一节:ch04a 什么是所有权

答案:借。不转移所有权,只是“借给你用一下“。

两条路:借用 或 克隆

两条路:借用 或 克隆。

借用(推荐)

fn main() {
    let s = String::from("hello");
    look(&s); // 把引用借出去,s 还是我的
    println!("{s} 还能用");
}

fn look(text: &String) {
    println!("只是看了一眼:{text}");
}

&s 是引用(reference),意思是“借给你看,但所有权还是我的“。 函数参数写成 &String 就表示“我要借一个 String“。

借用不转移所有权,所以借完还能用。

克隆(有代价,慎用)

fn main() {
    let s1 = String::from("hello");
    let s2 = s1.clone(); // 真的复制一份堆内存
    println!("{s1} 和 {s2} 都能用");
    println!("但它们是两块不同的内存");
}

对这里的 String,clone() 会复制字符串内容,非空字符串通常需要新的堆分配。 这里讨论的是 String 的克隆,不把这个行为推广到所有类型。

新手最容易犯的错:一看到报错就 clone()。 先问自己: “我是真的需要这份数据,还是只需要看一眼?” 只需要看一眼就传 &。

移动之后想拿回来

有时你确实要把值交出去,用完还想要回来。那就让函数再返回它:

fn main() {
    let s = String::from("hello");
    let s = add_world(s); // 交出去,再接回来(shadowing 覆盖原变量)
    println!("{s}");
}

fn add_world(mut text: String) -> String {
    text.push_str(", world");
    text // 返回它,所有权移回调用方
}

这有点绕。更常见的是传引用:

fn main() {
    let mut s = String::from("hello");
    add_world(&mut s); // 借出去让函数改
    println!("{s}"); // hello, world
}

fn add_world(text: &mut String) {
    text.push_str(", world");
}

注意这里的三个变化:

  1. let mut s —— 变量本身要可变
  2. &mut s —— 借一个“可以改的引用“
  3. text: &mut String —— 参数类型写成 &mut

借用有规则

& 可以借给很多人,&mut 同一时间只能有一个人:

fn main() {
    let mut s = String::from("hello");

    let r1 = &s;
    let r2 = &s;
    println!("{r1} {r2}"); // 多个只读借用,没问题

    let w = &mut s; // 只读借用结束后,可以借可变引用
    w.push_str("!");
    println!("{w}");
}

但这样不行:

fn main() {
    let mut s = String::from("hello");
    let r = &s;
    let w = &mut s;
    println!("{r} {w}");
}
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
 --> src/main.rs:4:13
  |
3 |     let r = &s;
  |             -- immutable borrow occurs here
4 |     let w = &mut s;
  |             ^^^^^^ mutable borrow occurs here
5 |     println!("{r} {w}");
  |                - immutable borrow later used here

规则:

同一时间,要么有任意多个 &T,要么有恰好一个 &mut T,不能同时。

两个 &mut 同时存在也是错的:

error[E0499]: cannot borrow `s` as mutable more than once at a time

为什么要有这条规则

如果一处代码通过引用读取数据,同时另一处代码修改同一份数据, 读取方就无法确定自己观察到的内容。可变借用要求独占访问,避免这种冲突。 前面的 String 例子已经展示:还要使用不可变引用时,就不能再借可变引用。

一个重要的细节:借用什么时候结束

借用并不一定持续到所在代码块结束。下面在只读引用最后一次使用后再修改字符串:

fn main() {
    let mut text = String::from("hello");
    let borrowed = &text;
    println!("{borrowed}"); // borrowed 最后一次使用
    text.push_str(" world");
    println!("{text}");
}

把 println!("{borrowed}") 移到 push_str 后面,就会产生借用冲突。

引用不能悬垂

前面的规则约束“谁能读、谁能改”;另一个约束是被引用的数据必须还活着。 如果数据先销毁,留下的引用就叫悬垂引用。安全 Rust 会拒绝这样的代码:

fn main() {
    let borrowed;
    {
        let owned = String::from("只在内层有效");
        borrowed = &owned;
    } // owned 已销毁
    println!("{borrowed}"); // 不能继续使用指向它的引用
}

同样,函数不能返回指向自己局部 String 的引用。如果调用方需要新创建的数据, 就返回拥有所有权的值:

fn make_text() -> String {
    String::from("把所有权交给调用方")
}

fn main() {
    let text = make_text();
    println!("{:?}", text); // 预期:"把所有权交给调用方"
    assert_eq!(text, "把所有权交给调用方");
}

这就是 ch10 生命周期要描述的事情:引用有效的时间不能超过数据有效的时间。

Slice:借用“一段“,而不是整个

对应原书 ch04-03 Slice 类型。

这一节回答一个很具体的问题:我想借用字符串(或数组)的一部分,怎么办?

什么是 slice

字符串切片借用字符串的一段,类型是 &str。

&str 就是“字符串切片“ —— 你现在明白这个类型名了: 它可以借用 String 的内容,也可以指向字符串字面量等其他有效的 UTF-8 数据。

fn main() {
    let s = String::from("hello world");

    // 各种切法
    let all: &str = &s[..]; // 整个
    let first: &str = &s[..5]; // 前 5 个字节
    let rest: &str = &s[6..]; // 从第 6 个字节到结尾
    let middle: &str = &s[3..8]; // 中间一段

    println!("[{all}] [{first}] [{rest}] [{middle}]");
}

注意切的是字节位置,不是字符位置 —— 这就是 ch08 会讲的那个坑: 对中文切片必须切在字符边界上,否则 panic。

只有 3 种省略写法:[..](全部)、[a..](从 a 到结尾)、[..b](从头到 b)。

先看不用 slice 会怎样

下面的 char_indices() 依次提供 (字节下标, Unicode 标量值), for (i, ch) 把这两个部分绑定给 i 和 ch。找到空格就返回下标,否则返回字节长度。

写一个“找第一个单词“的函数,能想到的最直接写法是返回下标:

// 返回第一个空格的位置(没有空格就返回长度)
fn first_space_index(s: &str) -> usize {
    for (i, ch) in s.char_indices() {
        if ch == ' ' {
            return i;
        }
    }
    s.len()
}

fn main() {
    let sentence = String::from("hello world");
    let end = first_space_index(&sentence);
    println!("第一个空格在下标 {end}");
}

能跑。但这个下标和字符串是脱钩的 —— 拿到它之后,你没法保证它还有意义:

// no_run:这段**能编译**,问题在运行时 —— 下面会 panic(这正是要说明的)
fn first_space_index(s: &str) -> usize {
    for (i, ch) in s.char_indices() {
        if ch == ' ' {
            return i;
        }
    }
    s.len()
}

fn main() {
    let mut sentence = String::from("hello world");
    let end = first_space_index(&sentence); // 算出来是 5

    sentence.clear(); // 字符串被清空了
    println!("第一个单词是:{}", &sentence[..end]); // 5 现在越界了!
}
thread 'main' panicked at src/main.rs:10:42:
byte index 5 is out of bounds of ``

问题在哪:end 只是一个数字,它和 sentence 没有任何关联。 字符串变了,数字不会跟着变,编译器也无法阻止你用这个过期下标。

正确的做法是返回一段借用:

// 返回第一个单词 —— 注意返回类型是 &str
fn first_word(s: &str) -> &str {
    for (i, ch) in s.char_indices() {
        if ch == ' ' {
            return &s[..i];
        }
    }
    s
}

fn main() {
    let sentence = String::from("hello world");
    let word = first_word(&sentence);
    println!("第一个单词是:{word}");
}

那这段借用挡住了什么

fn first_word(s: &str) -> &str {
    for (i, ch) in s.char_indices() {
        if ch == ' ' {
            return &s[..i];
        }
    }
    s
}

fn main() {
    let mut sentence = String::from("hello world");
    let word = first_word(&sentence);

    sentence.clear(); // ← 编译不过
    println!("第一个单词是:{word}");
}
error[E0502]: cannot borrow `sentence` as mutable because it is also borrowed as immutable
 --> src/main.rs:12:5
  |
11 |     let word = first_word(&sentence);
  |                                 -- immutable borrow occurs here
12 |     sentence.clear();
  |     ^^^^^^^^ mutable borrow occurs here
13 |     println!("第一个单词是:{word}");
  |                   ---- immutable borrow later used here

这是借用式 slice 的一个重要作用:word 是一个借用, 所以“清空 sentence“和“继续用 word“这两件事不可能同时发生 —— 编译器不允许。返回下标做不到这一点。

这就是 ch04 开头说的“用编译器保证内存安全“的具体样子。

数组切片

数组也可以借用其中一段,&[i32] 表示借用一段 i32 元素:

fn main() {
    let numbers = [10, 20, 30, 40];
    let part: &[i32] = &numbers[1..3];
    println!("{part:?}"); // [20, 30]
    println!("长度 {},第一个 {}", part.len(), part[0]);
}

切片保存起始位置和长度;它借用原数组,没有复制元素。

更常见的写法是 &str 而不是 &String:

fn main() {
    let s = String::from("hello");
    look(&s); // &String 能自动变成 &str

    let literal = "字面量也是 &str"; // 字符串字面量本身就是 &str
    look(literal);
}

fn look(text: &str) { // 用 &str 更通用
    println!("{text}");
}

为什么 &str 更好:它能接受 String 的借用,也能接受字符串字面量。 参数尽量用 &str,这是 Rust 的惯例。

三种得到 &str 的写法

fn main() {
    let s = String::from("hello");
    let a: &str = &s; // 最常见的写法(自动解引用)
    let b: &str = &s[..]; // 显式切片,效果一样
    let c: &str = s.as_str(); // 也可以

    println!("{a} {b} {c} 都一样");
}

三种写法等价,日常用 &s(最简洁)。

什么时候用 slice

场景用什么
函数只需要读字符串&str
函数只需要读一串数字&[i32]
要修改一段整数&mut [i32]

小结:判断该写什么的决策表

情况写什么
函数只需要读参数引用,例如 &i32、&str、&[i32]
函数需要修改参数可变引用,例如 &mut i32、&mut String
函数需要拿走字符串String(按值传,会移动)
需要一个能独立存在、不依赖原变量的副本.clone()

试一试

  1. 写一个接收 &String 的函数,调用后继续使用原字符串。
  2. 写一个接收 &mut String 的函数,为字符串追加 !。
  3. 同时创建两个可变引用并使用它们,读编译器的借用冲突错误。
  4. 创建不可变引用,先使用它,再修改字符串;调换顺序,比较编译结果。
  5. 写 fn first_word(s: &str) -> &str,用它借用一个 mut String 的首词; 在打印首词前调用原字符串的 clear(),观察借用冲突。这里清空的是原 String,不是只读的 &str。
  6. 把 [10, 20, 30, 40] 切成 [20, 30],再把这个切片传给函数并打印。

下一节:ch05 使用结构体组织相关联的数据