
References and Borrowing - brudgers
https://doc.rust-lang.org/book/references-and-borrowing.html
======
kibwen
I'm always up for talking about Rust, but I'm not sure what you're intending
to show by submitting a link to a specific page of the Rust book. :) Is there
something about references/borrowing in particular that you'd like to discuss
or present here?

~~~
markus2012
Here's something I find confusing about Rust references/borrowing. Please
correct me:

The '&' character does not seem to mean 'pass by reference' ala C++ - it
simply means borrow. Put another way, using '&' is not forcing the compiler to
pass a 64-bit pointer reference - Rust will ALWAYS memcpy() the params.

Rationale: existing Rust documentation states that both copy semantics and
move semantics are implemented with memcpy(): [http://doc.rust-
lang.org/std/marker/trait.Copy.html](http://doc.rust-
lang.org/std/marker/trait.Copy.html)

The only way to pass a reference (like C++) to a function seems to be by using
Box. This way Rust can memcpy() the Box struct - which is essentially a unique
pointer to some memory on the heap.

It works(?) this way because the called function may spawn a thread that
depends on one of the params. If such param was a reference/pointer to
something on the caller's stack and the caller's stack was unwound the
reference would be invalid.

I realize the borrow checker should be able to determine all of the lifetimes
and it should be able to pass pointers to data on the caller's stack in some
cases. Does Rust do this?

~~~
hetman
No, Rust invokes the equivalent of a memcpy() when moving ownership for types
with the Copy trait. A borrow is just like a pointer (and indeed you have to
dereference it with a * to get access to the contents).

~~~
markus2012
Ok, just to summarize:

foo(some_struct) == memcpy() for both copy and move.

foo(&some_struct) == copy usize ref/pointer value onto stack

So, mostly the same as C++. The exception is that Rust can use a ref under the
hood for foo(some_struct) if it wants.

