Rust References - Few points - Request for comments

Do not treat Rust references as pointers

They happen to be implemented using pointers on machine level, the same way C pointers happen to be implemented using integers on machine level. But pointers aren't just integers. References aren't just pointers.

  • Box<i32> is also a pointer. Its in-memory representation is identical to &i32. From C perspective, both pass data "by reference" exactly in the same way, and both would even work if passed to a C int* function.
  • Box<str> and &str are structs containing data pointer and a length. They can't be cast to a pointer.

Only shared borrows (&) are copyable. Exclusive borrows (&mut) are not (Rust does what it calls "reborrowing" to make them copyable-ish, but it's intentionally very limited).

References are about borrowing. They are about borrowing values, not variables, e.g. you can borrow a field of a struct. Some types even "fake" borrow things with zero-sized types like PhantomData just to enforce scopes or exclusive access to a shared resource.

Borrowing is a completely different angle that has no direct counterpart in C. If you try to think about it by analogy to C pointers, you're going to struggle with the borrow checker forever.

3 Likes