| Reason to Borrow |
|
it is very inconvenient to pass the ownership of a variable to another function and then return the ownership Rust supports the concept of borrowing the ownership of a value is transferred temporarily to an entity and then returned to the original owner entity below the main function invokes a function print_vector() a vector is passed as parameter to the print_vector function the ownership of the vector is also passed to the print_vector() function from the main() code will result in an error as shown below when the main() function tries to access the vector v fn main(){
// a list of nos
let v = vec![10,20,30];
print_vector(v);
println!("{}",v[0]); // this line gives error
}
fn print_vector(x:Vec
|
| What is Borrowing? |
|
when a function transfers its control over a variable/value to another function temporarily, for a while, it is called borrowing achieved by passing a reference to the variable (& var_name) rather than passing the variable/value itself to the function the ownership of the variable/value is transferred to the original owner of the variable after the called function returns fn main(){
// a list of nos
let v = vec![10,20,30];
print_vector(&v); // passing reference
println!("Printing the value from main() v[0]={}",v[0]);
}
fn print_vector(x:&Vec
error-free
|
| Mutable References |
|
a function can modify a borrowed resource by using a mutable reference to such resource a mutable reference is prefixed with &mut mutable references can operate only on mutable variables |
| Mutating an integer reference |
|
the main() function declares a mutable integer variable i and passes a mutable reference of i to the add_one() the add_one() increments the value of the variable i by one fn add_one(e: &mut i32) {
*e+= 1;
}
fn main() {
let mut i = 3;
add_one(&mut i);
println!("{}", i);
}
|
| Mutating a string reference |
|
the main() function passes a mutable reference of the variable name to the display() function the display function appends an additional string to the original name variable fn main() {
let mut name:String = String::from("TutorialsPoint");
display(&mut name);
//pass a mutable reference of name
println!("The value of name after modification is:{}",name);
}
fn display(param_name:&mut String){
println!("param_name value is :{}",param_name);
param_name.push_str(" Rocks");
//Modify the actual string,name
}
output
param_name value is :TutorialsPoint The value of name after modification is:TutorialsPoint Rocks |