Search code examples
rustmovebox

How can I pass a boxed member of a borrowed struct to a function without copying it?


In my example I get an error:

cannot move out of borrowed content

struct BigData {}

struct Data {
    x: Box<BigData>,
}

fn calc_data(x: Box<BigData>) {}

fn main() {
    let b = BigData {};
    let d = Data { x: Box::new(b) };
    let borrowed_d = &d;
    calc_data(borrowed_d.x); //error: cannot move out of borrowed content
}

playground


Solution

  • You can just borrow the boxed member and pass by reference:

    struct BigData {}
    
    struct Data {
        x: Box<BigData>,
    }
    
    fn calc_data(x: &Box<BigData>) {}
    
    fn main() {
        let b = BigData {};
        let d = Data { x: Box::new(b) };
        let borrowed_d = &d;
        calc_data(&borrowed_d.x);
    }
    

    playground

    But it's unlikely you actually want to pass a reference to the box rather than the BigData itself, so you can just do:

    fn calc_data(x: &BigData) {}
    

    and call it in the same way (&Box<T> automatically converts to &T).