4

The Rust Book mainly talks about move mechanics, but if I have a large structure I see that the Rust compiler produces code that copies the contents of the structure when I pass it by value to a function:

struct S2 {
    a: u64,
    b: u64,
    c: u64,
    d: u64,
    e: u64,
    f: u64,
    g: u64,
    h: u64,
    i: u64,
}

struct S {
    a: u64,
    b: u64,
    c: u64,
    d: u64,
    e: u64,
    f: u64,
    g: u64,
    h: u64,
    i: u64,
    s: S2,
}

fn xxx(xs: S) {
    println!("{:p}", &xs.s.a);
}

fn main() {
    let ms = S {
        a: 1,
        b: 1,
        c: 1,
        d: 1,
        e: 1,
        f: 1,
        g: 1,
        h: 1,
        i: 1,
        s: S2 {
            a: 1,
            b: 1,
            c: 1,
            d: 1,
            e: 1,
            f: 1,
            g: 1,
            h: 1,
            i: 1,
        },
    };
    println!("{:p}", &ms.s.a);
    xxx(ms);
}

In the output, I see that Rust didn't optimize the move of ms to the function parameter xs to use a pointer, but rather copied the entire thing. I used opt-level=3:

$ ./test
0x7ffeea23a8a8
0x7ffeea23a818

Is this something I should worry about? Is it recommended to use Box for large structs?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
599644
  • 561
  • 2
  • 15
  • 1
    Also relevant: [Box vs move semantics on X](https://stackoverflow.com/questions/37125998/boxx-vs-move-semantics-on-x). – ljedrz Jun 24 '18 at 05:26

0 Answers0