下面的code会触发描述良好的cannot borrow as immutable because it is also borrowed as mutable错误:
let mut buf = [0; 128];
let p = &mut buf[0..buf.len()];
error[E0502]: cannot borrow `buf` as immutable because it is also borrowed as mutable
--> src/main.rs:3:25
|
3 | let p = &mut buf[0..buf.len()];
| -------^^^-------
| | | |
| | | immutable borrow occurs here
| | mutable borrow later used here
| mutable borrow occurs here
我理解产生这个错误的机制,但是编译器不是以错误的方式看待这个问题吗?
在获取数组的可变borrow 之前,必须解析该范围.因此,在可变借入可以发生之前,它必须已经获得了不可变的借入、运行len()
、检索了长度并释放了不变借入来创建范围.
在知道范围之前获取可变借入是没有意义的.
这是实现对生命周期的限制(例如,类似于non-lexical lifetimes最终解决的问题),还是故意这样做?