Hoping for clarity on how Rust works in these situations

3 years ago by nerdblood to c/rust

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:

  1. 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?

load all comments
KillTheMule 5 points 3 years ago

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?

I don't understand this. Shared references to String are Copy, too. This doesn't have to do anything with sizes. Rather, it's implemented in the compiler, because it's sound to have it and a huge QoL improvement over the alternative... just the same reason why e.g. usize is Copy, really.

is it dereferenced specifically because is Boxed on the heap?

No, it's not really related to the heap. Box implements DerefMut, which is in-depth explained here.

path: 0 4730097, hotness: undefined, score: 5, children: 0
rust
rust

@programming.dev

login for more options
8334
1423
293

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits
  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

go to feed...