Hello, Coders! Today, we'll examine two intriguing Rust concepts: variable references and mutable references, essential for efficient memory management. You'll learn about them through an example of Rust code employing mutable references. Off we go!
Imagine we're stepping into the world of Rust's pointers, which act as directional signs to memory locations, much like addresses in a neighborhood.
A variable reference is like having a house address—it guides you to where the house is located. Just as you can visit and look at the house based on its address, but not alter it, a variable reference allows you to see a value without changing it.
To create a reference to a variable, add & before the variable name.
To dereference a variable and get the value of a reference variable, add * before the variable name.
Here's how we might express this in Rust:
In this case, y has the "address" that points to where x is in memory, much like having directions to a house. z contains the value stored at y.
Consider this scenario in Rust:
Here, we start by creating a mutable variable x with a value of 5. We then copy the value of x into a new variable y. When we increase the value of y by 1, x remains unchanged. The reason is that y is an entirely separate copy of x's value. It's like if you copied your friend's house key; changing the lock on your own house doesn't change the lock on your friend's house.
Now, let's look at mutable references:
In sharp contrast with our earlier code, y here is not a copy of x's value but a mutable reference to x—it's as if you have the key to actually unlock and alter what's inside x's house.
In our house metaphor, if the variable reference is like knowing the address of a house, then *y is akin to opening the door with a key and stepping inside. Once inside, you can rearrange the furniture or repaint the walls, essentially altering the state of the house's interior.
If we then execute an action, like *y += 1;, we're not just looking at the house from the outside, we're changing something inside the house – specifically, we're incrementing the value that x holds. So, x's value changes because we've used our key (the mutable reference pointed to by y) to go inside and make an update.
