Hacker News new | ask | show | jobs
by markus2012 3869 days ago
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

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?

2 comments

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).
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.

You're mis-understanding.

  > Rust will ALWAYS memcpy() the params.
Right. This is "pass value by reference." The reference itself, the pointer, gets copied. Not what it points to.

  > Does Rust do this?
Rust's ABI is undefined, so officially, it doesn't do anything. That said, currently, it will take larger items and pass a pointer instead, if it makes sense to do so.