How come this builds:
let len = file.read(&mut buf)?;
let curslice = &buf[..len];
play
But this doesn't?
let curslice = &buf[..file.read(&mut buf)?];
play
I mean, sure, I get that the mutable borrow is held for the entire duration of the statement so the immutable borrow can't happen, but... the mutable borrow clearly isn't needed anymore so why not just end its lifetime before the immutable starts? I thought Non-Lexical Lifetimes was implemented to fix things like that. What gives?
This is basically the same as this, but with the borrow types flipped
opened 11:54AM - 02 Jun 16 UTC
A-borrow-checker
T-compiler
C-bug
I have the following piece of code which I expect to work but the borrow checker… does not agree:
```
fn main() {
let mut data = vec![1; 100];
{
let (left, right) = data.split_at_mut(data.len() / 2);
}
println!("{:?}", data);
}
```
Please note that the extra scope is in principle not related to the issue I'm describing, I'm just doing it such that I can use the `println!` macro to ensure that the compiler does not optimize the code away because I'm not using it thereafter. (I'm new to Rust so I don't know the exact rules)
The error I get is the following:
```
main.rs:4:47: 4:51 error: cannot borrow `data` as immutable because it is also borrowed as mutable [E0502]
main.rs:4 let (left, right) = data.split_at_mut(data.len() / 2);
^~~~
main.rs:4:29: 4:33 note: previous borrow of `data` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `data` until the borrow ends
main.rs:4 let (left, right) = data.split_at_mut(data.len() / 2);
^~~~
main.rs:5:6: 5:6 note: previous borrow ends here
main.rs:3 {
main.rs:4 let (left, right) = data.split_at_mut(data.len() / 2);
main.rs:5 }
^
```
However what I would expect is the following:
1. `data.len()` takes an immutable borrow.
2. `data.len()` returns the immutable borrow and divides the obtained `u32` by `2`.
3. `data.split_at_mut()` takes a mutable borrow.
It seems like the borrow checker currently evaluates the statement in the wrong order.
The following workaround is available, but it feels like this is a place where we should not have the need to (rightfully) fight the borrow checker.
```
fn main() {
let mut data = vec![1; 100];
{
let len = data.len();
let (left, right) = data.split_at_mut(len / 2);
}
println!("{:?}", data);
}
```
system
Closed
March 24, 2020, 6:49am
3
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.