7

Am I correct to assume that, for the following code

let a = vec![1, 2, 3];
let b = &a;
let c = b;

The memory presentation will be something like this, assuming the value of b is "B"?

  _            _
b|B|         c|B|
  |____________|
  |
  V
  _________
a|_________|

I'm only asking about immutable references, as there can be only 1 mutable reference, as far as I remember.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Exander
  • 852
  • 1
  • 7
  • 17
  • 1
    See also [Do all primitive types implement the Copy trait?](http://stackoverflow.com/q/41413336/155423) – Shepmaster Mar 30 '17 at 18:31
  • See also [Copy/move semantics documentation of &T/&mut T types itself](http://stackoverflow.com/q/37381212/155423) – Shepmaster Mar 30 '17 at 18:32

1 Answers1

9

Yes, this is correct.

In Rust terms, &T is Copy, which means that it can be copied bitwise without transferring ownership.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • 1
    But &mut T is moved, right? – Exander Mar 30 '17 at 18:20
  • @Exander: Yes, this is necessary to ensure **Aliasing XOR Mutability**. – Matthieu M. Mar 30 '17 at 18:28
  • Thoughts on marking this as a duplicate to the second comment I added on OP? – Shepmaster Mar 30 '17 at 18:33
  • @Shepmaster: Does look like a dupe indeed, I'll leave you the honour since you hunted it down. – Matthieu M. Mar 30 '17 at 18:46
  • @Shepmaster: I agree, and thank you all for your explanations. – Exander Mar 30 '17 at 18:48
  • Are lifetimes copied as well when a reference is copied? Or can the copy have an different lifetime compared to the original reference? – raj Sep 25 '21 at 12:02
  • 2
    @raj: Excellent question. The lifetime is part of the _type_ and therefore is copied too. However when calling a function, Rust may "align" lifetimes, possibly by re-borrowing, so it may look like the lifetime changed which may be where your confusion stems from. – Matthieu M. Sep 25 '21 at 12:30