I am trying to have a function copy some data into a mutable slice that is passed in and then also shrink the size of that slice to the actual size of the data. However, it does not work because of lifetime issues.
Is something like this possible in safe Rust? (Playground)
fn read_into<'a>(output: &'a mut &'a mut [u8]) -> bool {
static input: [u8; 8] = [0x01u8; 8];
if input.len() > output.len() {
return false
}
output[0..input.len()].copy_from_slice(&input);
*output = &mut output[0..input.len()];
true
}
fn main() {
let mut buffer = [0x00u8; 16];
println!("buffer.len() = {}", buffer.len());
let mut alias = &mut buffer[..];
println!("alias.len() = {}", alias.len());
println!("alias = {:?}", alias);
read_into(&mut alias);
println!("alias.len() = {}", alias.len());
println!("alias = {:?}", alias);
}
error[E0502]: cannot borrow `*alias` as immutable because it is also borrowed as mutable
--> src/main.rs:18:35
|
17 | read_into(&mut alias);
| ---------- mutable borrow occurs here
18 | println!("alias.len() = {}", alias.len());
| ^^^^^
| |
| immutable borrow occurs here
| mutable borrow later used here
error[E0502]: cannot borrow `alias` as immutable because it is also borrowed as mutable
--> src/main.rs:19:37
|
17 | read_into(&mut alias);
| ---------- mutable borrow occurs here
18 | println!("alias.len() = {}", alias.len());
19 | println!("alias = {:?}", alias);
| ^^^^^
| |
| immutable borrow occurs here
| mutable borrow later used here