DEV Community

Cover image for ✨♻️ Rust Visualized: Pointers as References
ender minyard
ender minyard

Posted on

✨♻️ Rust Visualized: Pointers as References

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.

pointer1

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.

pointer2

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.

1

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.
ahh

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.

borrow_example

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].

carbon

Discussion (2)

Collapse
jdeepd profile image
JDeep

Nice article. How are you creating the GIFs though?

Collapse
ender_minyard profile image
ender minyard Author

Keynote!