What happens when pointers are returned in rust?

I am reading some of the return pointers in the Rust manual. Here's some sample code:

struct BigStruct {
    one: int,
    two: int,
    // etc
    one_hundred: int,
}

fn foo(x: Box<BigStruct>) -> BigStruct {
    return *x;
}

fn main() {
    let x = box BigStruct {
        one: 1,
        two: 2,
        one_hundred: 100,
    };

    let y = box foo(x);
}

      

The strong part of the following explanation confuses me:

There is no copy in this code. main allocates enough space for the window, passes a pointer to that memory to foo as x , and then foo writes the value directly to that pointer. This writes the return value directly to the highlighted field.

after reading the linked question , I still don't get a point without a copy here.

Does the function return a foo

copy *x

? If so, how do you understand the explanation? If not, is it related to ownership and borrowing?

I understand the concept of ownership and borrowing, I just don't know when it will happen.

+3


source to share


1 answer


The manual is trying to tell you that the code behaves as if it were written like this:

struct BigStruct {
    one: int,
    two: int,
    // etc
    one_hundred: int,
}

fn foo(x: Box<BigStruct>, result: &mut BigStruct) {
    *result = *x;
}

fn main() {
    let x = box BigStruct {
        one: 1,
        two: 2,
        one_hundred: 100,
    };

    unsafe {
        let mut y = box std::mem::uninitialized();
        foo(x, &mut *y);
    }
}

      

main

creates Box

and passes a pointer to the inner area of ​​the window foo

as an input argument. Thus, foo

can store the value of the result directly, rather than return it, and main

copy it into the field.

A foo

copy is executed in (from the first field to the second block), but if it was foo

not written directly to the field, there would be two copies (perhaps one from the first line for stack in foo

, then from the stack in the second block in main

).



PS: I think there is a mistake in the manual. It says:

passes a pointer to this memory to foo as x

but x

- this is the field we are trying to copy from, not the new field ... Rather, it passes the pointer as a hidden argument.

+4


source







All Articles