1

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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Alexander Theißen
  • 3,799
  • 4
  • 28
  • 35
  • 2
    Does [How can I modify a slice that is a function parameter?](https://stackoverflow.com/q/34384089/155423) answer your question? – Shepmaster Jul 22 '20 at 16:52
  • 2
    The [duplicate applied to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0989ebb0b5a18af044e8784265557f94). – Shepmaster Jul 22 '20 at 17:10

0 Answers0