References – safe pointers

These pointers are already familiar to you from the borrowing section. References are like pointers in C, but they are checked for correctness. They can never be null and always point to some data owned by any variable. The data they point to can either be on the stack or on the heap, or the data segment of the binary. They are created using the & or the &mut operator. These operators, when prefixed on a type T, create a reference type that is denoted by &T for immutable references and &mut T for mutable references. Let's recap on these again:

  • &T: It's an immutable reference to a type T. A &T pointer is a Copy type, which simply means you can have many immutable references to a value T. If you assign this to another variable, you get a copy of the pointer, which points to the same data. It is also fine to have a reference to a reference, such as &&T.
  • &mut T: It's an immutable pointer to a type T. Within any scope, you cannot have two mutable references to a value T, due to the borrowing rule. This means that &mut T types do not implement the Copy trait. They also cannot be sent to threads.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset