-1

I have a struct (Data) from an external crate, which is therefore unchangeable, which references a mutable array. Now I want to return an instance of that struct, but can't, because it references a local variable. Experiments with Rc<RefCell<>>, Box, etc. weren't working, I couldn't tie the lifetime of data and bytes together. Rust insists on destroying bytes when leaving the function, which collides obviously with the returned data.

Most other solutions to similar questions I found were solved by either changing Data (impossible), or by heavily restructuring the surrounding code, because someone misunderstood something completely.

The only one actually solving the problem was this: https://stackoverflow.com/a/72118480/6659960 (Big thanks). I had a hard time finding it and deciphering it, that it solved my problem. This Q&A is much clearer and shorter, so it can be far better understood.

I had exactly this problem:

// Can't change this!
pub struct Data<'a> {
    data: &'a mut [u8],
}

// Can't change this!
impl Data<'_> {
    fn do_it(&mut self) {
        self.data[20] = 23;
    }
}

// This is up to me:
fn test<'a>() -> Data<'a> {
    let mut bytes: Vec<u8> = vec!(0; 128);
    let mut data = Data {
        data: &mut bytes
    };
    data.do_it();

    /*
    Next line fails of course with:
     data: &mut bytes
           ---------- `bytes` is borrowed here

     data
     ^^^^ returns a value referencing data owned by the current function
    */
    data
}

1 Answers1

0

Here the short answer, reduced to essentials:

Provide the variable from the outside, so it stays alive. Create it outside as cheap as possible, dereference it inside the function and reassign the dereferenced variable.

Code:

fn test(bytes: &mut Vec<u8>) -> Data {
    *bytes = vec!(0u8; 128);
    let mut data = Data {
        data: bytes
    };
    data.do_it();
    data
}

fn call() {
    let mut v: Vec<u8> = Vec::default();
    let result = test(&mut v);
}