Borrowing In Rust
In this article, we will learn about borrowing in Rust. In Ownership In Rust, we have learned that only a single variable can hold the ownership of data on the heap at a time.
Before starting
the discussion of borrowing, we should understand that assigning a
variable to another variable, passing a variable as an argument to a
function, and assigning the return value of a function to a variable are
the same.
Another concept of scope is also very important. In
Rust, the last use of a variable defines the scope of the variable. In
other words, the scope of a variable ends when it is used the last time
in a function.
When we assign a variable that points to data
on the heap to another variable, it transfers ownership of the data to
another variable. As we have read above, ownership is also transferred
in the case of an argument passing to a function and returning a value
from the function.
To get rid of the situation, where
ownership is transferred to a function and again returned from the
function, we use borrowing.
fn main() {
let str = String::from("theloveoftechI");
let ref_str = &str;
let ref1_str = &str;
println!("{ref_str}, {ref1_str}");
let mut str1 = String::from("theloveoftechI");
let mref_str1 = &mut str1;
mref_str1.push_str(" on Twitter");
println!("{mref_str1}"); //1
//let ref1_str1 = &str1;//2
//println!("{mref_str1}"); //3
}As we see in the image above, ref_str has no ownership of the data on the heap rather it points to str. So when ref_str goes out of the scope no drop method will be called. We can take multiple immutable references at the same time.
If we want to change the data on the heap using a reference then we have to take a mutable reference. First, we have declared str1 as mutable and used &mut str1 to take a mutable reference. We can not use any other references while using a mutable reference. So, in line //2,we are taking an immutable reference along with a mutable reference which is wrong. In line //1, the use of mref_str1 is right because it is being used before the declaration of the other reference.
But, in line //3, it is wrong. We have read above that scope of a variable ends when it is used last time. In line //3, an immutable reference exists along with the mutable reference.
Happy reading. Keep in touch.

Comments
Post a Comment