This content originally appeared on DEV Community and was authored by ender minyard
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.
? References
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.
Using &
or &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.
At any given time, you can have one mutable reference to a value or an infinite amount of immutable references to a value.
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.
In 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.
? Slices
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 &word[starting_index...last_index_plus_one]
.
This content originally appeared on DEV Community and was authored by ender minyard
ender minyard | Sciencx (2021-08-29T15:35:06+00:00) ✨♻️ Rust Visualized: Pointers as References. Retrieved from https://www.scien.cx/2021/08/29/%e2%9c%a8%e2%99%bb%ef%b8%8f-rust-visualized-pointers-as-references/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.