I’m slowly starting Rust for Rustaceans, and it’s already poking holes in my understanding of Rust. Here’s a couple initial questions I have:

A shared reference, &T is , as the name implies, a pointer that may be shared. Any number of references may exist to the same value, and each shared reference is Copy, so you can trivially make more of them

I don’t understand why a shared reference has to implement copy. In fact, isn’t this not true just by the fact that references work for Strings and Strings size can’t be known at compile time?

  1. I’m having trouble with the idea of assigning a new value to a mutable reference.

let mut x = Box::new(42); *x = 84;

Why in this example, is the assignment dereferenced. Why not just do x=84? is it dereferenced specifically because is Boxed on the heap?

  • @nerdbloodOP
    link
    2
    edit-2
    11 months ago

    So, for #1, it is not saying that T implements Copy, it is saying that regardless of what T is, &T implements Copy. This is because, by definition, it is always valid to copy a shared reference, even if T itself is not Copy.

    Got it! this helps a lot, thanks. I think I was indeed thinking of it as some kind of pseudo type and not a type in of itself. I got a little lost in the further explanation, but I really need to spend more time understanding Clone and Copy in general. Thanks!

    • @BatmanAoD
      link
      111 months ago

      It’s totally reasonable to assume that &T is a “pseudo-type”; that’s very much what it is in C++, and there aren’t any other mainstream languages with that syntax to compare against!