Rules of References


#1

Rules of references are little tricky for me, especially because of the wording… Just to summarize, will I be wrong if I say,

  • References must be valid
    and
  • In a given scope, there must be either
    • One mutable reference
      or
    • Any number of immutable reference

#2

Certainly the second point you make is true. Regarding the first point, I’m not even sure the compiler will let you have an invalid reference, so I don’t think that could even happen in a compiled program.

The best place I’ve found to learn about references and how they also affect access (also with regard to ownership) is in the Programming Rust by Blandy et al, that aren’t mentioned in the online book but are super important.

For example, what I didn’t know was that you can declare a value as immutable, but then later borrow a mutable reference to it, and modify it. <- EDIT: This is not true, I was mistaken.


#3

Is that actually possible? Wouldn’t that make the system unsound immediately?


#4

@rayascott must be referring to shadowing:

let s = "hello".to_string();
let mut s = s;
foo(&mut s);

fn foo(s: &mut String) {} 

#5

Perhaps goes without saying, but just to be clear: safe code will not allow it, but you can forge invalid references with unsafe code.