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?

  • snaggen@programming.dev
    link
    fedilink
    arrow-up
    5
    ·
    edit-2
    1 year ago

    A reference &T holds a pointer, ie. the memory adress to the actual content of T

    So, in the example x doesn’t hold the value 42, it holds the memory adress to the memory there the integer value 42 is stored. So, to access the value, you need to dereference the reference. Which is why you need to use *x when you assign the value.

      • KillTheMule@programming.dev
        link
        fedilink
        arrow-up
        4
        ·
        edit-2
        1 year ago

        A reference IS Copy, by the simple fact that it is a primitive value on the stack.

        This seems a bit misleading, noting that unique/mutable references aren’t Copy. Shared references are Copy because it’s sound to have that, and it’s a huge QOL improvement over the alternative.