Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 29, 2021 03:35 pm GMT

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


Original Link: https://dev.to/ender_minyard/rust-visualized-pointers-as-references-23cg

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To