[ PROMPT_NODE_24710 ]
rust
[ SKILL_DOCUMENTATION ]
# Rust 错误模式
常见的 Rust 错误及其诊断与解决方案。
## 所有权错误
### cannot move out of borrowed content
rust
error[E0507]: cannot move out of borrowed content
--> src/main.rs:5:9
|
5 | let s = &vec[0];
| ^^^^^^^ cannot move out of borrowed content
**解决方案**:
rust
// 如果需要则克隆
let s = vec[0].clone();
// 或者借用而不是移动
let s = &vec[0];
// 使用 .get() 获取 Option
if let Some(s) = vec.get(0) {
// 将 s 作为引用使用
}
---
### cannot borrow as mutable because it is also borrowed as immutable
rust
error[E0502]: cannot borrow `x` as mutable because it is also borrowed as immutable
**原因**:
1. 可变借用和不可变借用重叠
2. 迭代器失效
**解决方案**:
rust
// 错误
let r1 = &vec;
let r2 = &mut vec; // 错误!
// 正确 - 先结束不可变借用
let r1 = &vec;
println!("{:?}", r1); // r1 的最后一次使用
let r2 = &mut vec; // 现在可以了
// 对于集合,使用索引代替
let len = vec.len();
for i in 0..len {
vec[i] += 1; // 正确
}
// 或者使用内部可变性
use std::cell::RefCell;
let vec = RefCell::new(vec![1, 2, 3]);
---
### cannot borrow as mutable more than once
rust
error[E0499]: cannot borrow `x` as mutable more than once at a time
**解决方案**:
rust
// 错误
let r1 = &mut vec;
let r2 = &mut vec; // 错误!
// 正确 - 限制第一个借用的作用域
{
let r1 = &mut vec;
// 使用 r1
} // r1 超出作用域
let r2 = &mut vec; // 现在可以了
// 或者对切片使用 split_at_mut
let (left, right) = slice.split_at_mut(mid);
---
### value borrowed here after move
rust
error[E0382]: borrow of moved value: `s`
**解决方案**:
rust
// 错误
let s = String::from("hello");
let s2 = s;
println!("{}", s); // 错误!s 已被移动
// 选项 1: 克隆
let s = String::from("hello");
let s2 = s.clone();
println!("{}", s); // 正确
// 选项 2: 使用引用
let s = String::from("hello");
let s2 = &s;
println!("{}", s); // 正确
// 选项 3: Copy 类型 (实现 Copy trait)
let x = 5;
let y = x;
println!("{}", x); // 正确,i32 是 Copy 类型
---
## 生命周期错误
### missing lifetime specifier
rust
error[E0106]: missing lifetime specifier
--> src/main.rs:1:17
|
1 | fn longest(x: &str, y: &str) -> &str {
| ---- ---- ^ expected named lifetime parameter
**解决方案**:
rust
// 添加生命周期注解
fn longest(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {