Rust - Borrowing Flashcards
What is borrowing
It is basically passing ownership temporarily. Accessing data without taking ownership over it.
How do you borrow
By passing by reference.
Give example of wrong use of borrow
fn main(){
let v = vec![10,20,30];
print_vector(v);
println!(“”, v);
}
Give example of how to borrow
fn main () {
let v = vec![10,20,30];
print_vector(&v);
println!(“Printing the value from main() v[0]={}”,v[0]);
}
fn print_vector(x:&Vec<i32>){
println!("Inside print_vector function {:?}",x);
}</i32>
How to mutate a reference
fn add_one(e: &mut i32) {
*e+= 1;
}
fn main() {
let mut i = 3;
add_one(&mut i);
println!(“{}”, i);
}
How to mutate a string refernce
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
}