所有权、借用和切片

2026-11-27 · Rust · Rust入门

实验环境:rustc / cargo 1.93(Linux),文中代码、报错与输出均为实测。

这篇讲所有权和借用。

它管的是什么

Rust 不用垃圾回收(GC),也不让你手动 free。内存管理交给编译器:每个值在任何时刻只有一个拥有者,当这个拥有者离开作用域时,值被自动释放。

栈和堆要分清。栈是每次函数调用分配的固定大小的区域;堆是运行时动态分配的内存,值放在那里、用指针访问。长度在编译期定不下来的类型(比如 String)就放堆上:

fn main() {
    {
        let s = String::from("hello"); // s 从这里开始有效
    }                                  // s 离开作用域,内存在这里释放
}

这段能正常编译,没有输出。关键在那个右花括号:s 出了作用域,Rust 自动释放了堆上的字符串。

Move:值只有一个主人

下一段会报错:

fn main() {
    let s1 = String::from("hello");
    let s2 = s1;            // 所有权从 s1 转给 s2
    println!("{s1}, world!");   // 这行编译不过
}

报错原文:

error[E0382]: borrow of moved value: `s1`
 --> main.rs:4:16
  |
2 |     let s1 = String::from("hello");
  |         -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 |     let s2 = s1;        // value moved into `s2`
  |              -- value moved here
4 |     println!("{s1}, world!");
  |                ^^ value borrowed here after move

s2 = s1 是把所有权整个转移给 s2,不是复制一份。转移之后 s1 失效,再使用它就编译不过。Rust 不会偷偷帮你深拷贝堆内存:如果每次赋值都悄悄分配、释放,性能问题反而更难查。想复制就显式调用 .clone();否则被移动之后就不能再使用原值了。

整数这类类型实现了 Copy trait,赋值是真拷贝而不是移动:

fn main() {
    let x = 5;
    let y = x;          // i32 是 Copy,这里复制,不转移所有权
    println!("{x}, {y}");   // 正常输出 5, 5
}

函数也会移走参数

把值传给函数,同样是转移所有权:

fn main() {
    let s = String::from("hello");
    takes_ownership(s);   // s 进函数就被移走了
    println!("{s}");      // 又是 E0382
}

fn takes_ownership(some_string: String) {
    println!("{some_string}");   // some_string 出作用域,字符串被释放
}

报错里有条提示:

note: consider changing this parameter type in function `takes_ownership` to borrow instead if owning the value isn't necessary
 --> main.rs:7:33
  |
7 | fn takes_ownership(some_string: String) {
  |    ---------------              ^^^^^^ this parameter takes ownership of the value

意思是:如果只是想用一下这个值、不必拥有它,就把参数改成引用。

引用:只借不拿走

如果只想算个长度、不想把字符串传进去,可以用引用(reference):只使用一个值而不拿走它。

fn main() {
    let s1 = String::from("hello");
    let len = calculate_length(&s1);   // & 是"借一下",不转移所有权
    println!("The length of '{s1}' is {len}.");   // s1 还有效
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

运行结果:The length of 'hello' is 5.。这里 &s1 表示函数拿的是地址不是值本身;用完就还,所以 s1 在调用之后照样能用。

引用也有两条规则

引用有两条规则。第一,引用必须始终有效,不能指向已经释放的东西。第二,同一份数据要么允许任意多个只读引用,要么只允许一个可变引用,这两种情况不能同时存在。第二条最容易出错:

fn main() {
    let mut s = String::from("hello");
    let r1 = &s;      // 只读引用开始
    let r2 = &s;      // 再来一个只读,没问题
    let r3 = &mut s;  // 想改它:编译不过(E0502)
    println!("{r1}, {r2}, {r3}");
}

报错原文:

error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
 --> main.rs:5:14
  |
3 |     let r1 = &s;      // immutable borrow begins
  |              -- immutable borrow occurs here
4 |     let r2 = &s;      // another immutable borrow is fine
5 |     let r3 = &mut s;  // mutable borrow while immutably borrowed -> compile error
  |              ^^^^^^ mutable borrow occurs here
6 |     println!("{r1}, {r2}, {r3}");
  |                -- immutable borrow later used here

只要只读引用还在使用,就不许再开一个可变引用。原因是:一边在写、另一边在读同一块数据时,会读到改了一半的状态,这正是 C/C++ 里数据竞争(data race)的来源。Rust 在编译期拦掉这类问题,能过编译的代码基本不存在数据竞争。

别返回局部变量的引用

下面这个函数想返回字符串的引用,但那个字符串是函数内的局部变量:

fn dangle() -> &String {
    let s = String::from("hello");
    &s            // 返回对 s 的引用;可 s 在函数结束时就释放了
}

它编译不过(E0106)。返回一个指向即将被释放的值的引用是不安全的:要么返回值本身(fn dangle() -> String),要么给引用加上生命周期标注去说明它能活多久。生命周期的具体写法这里不展开。

切片(slice)

切片是引用一段连续的元素——比如数组或字符串的一部分。它本质上是一种引用,所以不拥有这些数据。

为什么需要它?假设要返回一个字符串里的第一个单词,只返回一个下标(比如 5)不够:这个数离开那个 String 就没有意义了,内容一变下标就失效。切片把"起点 + 长度"打包成一个和底层数据绑定的值,就不会跑偏。

fn main() {
    let s = String::from("hello world");
    let hello = &s[0..5];   // "hello"
    let world = &s[6..11];  // "world"
    println!("{hello} {world}");
}

[起点..终点],终点是最后一个位置的下一位(不含它)。简写:起点是 0 就省掉前面的数(&s[..5]),要取到末尾就把结尾省掉(&s[3..]),整段就是 &s[..]。

fn main() { let s = String::from("hello"); let a = &s[..2]; let b = &s[3..]; println!("{a} {b}"); }   // he lo

注意 UTF-8 边界:字符串切片的下标必须落在合法字符边界上,不能从多字节字符中间切开。对 "山" 做 &s[0..1] 会在运行期 panic(byte index 1 is not a char boundary)。

数组等集合也能切片,类型写成 &[i32]:

fn main() { let a = [1, 2, 3, 4, 5]; let slice = &a[1..3]; println!("{:?}", slice); }   // [2, 3]

顺带说清一件事:字符串字面量 "hello" 的类型本身就是 &str——一个指向程序二进制的切片,所以它是不可变的。

动手实践

别只看不练,把上面的代码一个个敲出来跑,尤其是会报错的几段。看编译器指出哪一行、为什么报,比反复读解释更有效。当你能在脑子里判断 E0382 会在哪一行报出来,说明这块已经掌握了。

© 2026 michaelfu'site 原创文章,转载请注明出处:https://michaelfu.site/posts/2026-11-27-rust-ownership.html

← 返回首页