How do we visualize pointers?
A pointer points ➡️ to a location in memory. This location in memory contains information that is of interest to us.
You can think of the table of contents in a book containing pointers to the chapters in that book.
The table of contents in a book points you to where the chapters in the book are. The pointers don't actually contain the data they are pointing to.
In Rust, this type of pointer is a reference to some other data.
A book that has six chapters gets edited and the sixth chapter is removed. Now, if the table of contents points to Chapter 6 but the book only has 5 chapters, the table of contents is wrong.
A reference to a location in memory that has been cleaned up is an invalid reference.
Rust has mutable and immutable references. Mutable references allow you to change the value they point to, but immutable references just let you see the value they point to.
&mut points to memory owned by some other value.
If you try to make immutable and mutable references to the same value at the same time, your code will not compile.
Where does the idea of borrowing come from? You can reference values and make use of those references, but your use of these references is temporary.
When you have a reference to another value as the parameter of a function in Rust, you do not own that value, you're just borrowing it. When you borrow something, you have to give it back.
If you're borrowing a value at the start of a function, you have to give it back at the end of the function.
calculate_length(s: &String), the function's parameter
s is a reference to a string. At the end of
calculate_length(s: &String), the memory allocated to
s gets cleaned up. Because
s is just a reference to
String, nothing happens.
What if you need to reference part of something instead of the entire thing? This is where the slice type becomes useful. In Rust, you create string slices by writing