无标题
今日大战borrow checker:
enum E {
A(usize),
B,
}
struct S {
x: i32,
e: E,
}
fn f(s: &mut Vec<S>) {
match &s[0].e {
E::A(index) => s[*index].x = 114514,
_ => {}
}
}
error[E0502]: cannot borrow `*s` as mutable because it is also borrowed as immutable
--> src/main.rs:13:24
|
12 | match &s[0].e {
| - immutable borrow occurs here
13 | E::A(index) => s[*index].x = 114514,
| ^ ------ immutable borrow later used here
| |
| mutable borrow occurs here
|
= help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices
此处同时持有不可变引用和可变引用理论上没有问题,因为读的是e而写的是x。
编译器提示的split_at_mut并不完全适用,因为index可能是0。
最后我写出了一段超级抽象的match match:
fn f(s: &mut Vec<S>) {
match match &s[0].e {
E::A(index) => Some(*index),
_ => None,
} {
Some(index) => s[index].x = 114514,
None => {}
}
}
以上是在实现Crafting Interpreters § 25.3之OP_SET_UPVALUE指令时遇到的问题。函数和闭包两章给我写到怀疑人生了 😾 指针乱飞,生命周期一桶浆糊,怪不得用Rust写clox的最后都坑掉了 😾