Why does “move” in Rust not actually move?

后端 未结 1 1076
暖寄归人
暖寄归人 2020-12-30 08:25

In the below example:

struct Foo {
    a: [u64; 100000],
}

fn foo(mut f: Foo) -> Foo {
    f.a[0] = 99999;
    f.a[1] = 99999;
    println!(\"{:?}\", &am         


        
相关标签:
1条回答
  • 2020-12-30 08:35

    A move is a memcpy followed by treating the source as non-existent.

    Your big array is on the stack. That's just the way Rust's memory model works: local variables are on the stack. Since the stack space of foo is going away when the function returns, there's nothing else the compiler can do except copy the memory to main's stack space.

    In some cases, the compiler can rearrange things so that the move can be elided (source and destination are merged into one thing), but this is an optimization that cannot be relied on, especially for big things.

    If you don't want to copy the huge array around, allocate it on the heap yourself, either via a Box<[u64]>, or simply by using Vec<u64>.

    0 讨论(0)
提交回复
热议问题