Rust - Borrowing Flashcards

1
Q

What is borrowing

A

It is basically passing ownership temporarily. Accessing data without taking ownership over it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you borrow

A

By passing by reference.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give example of wrong use of borrow

A

fn main(){
let v = vec![10,20,30];
print_vector(v);
println!(“”, v);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Give example of how to borrow

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to mutate a reference

A

fn add_one(e: &mut i32) {
*e+= 1;
}
fn main() {
let mut i = 3;
add_one(&mut i);
println!(“{}”, i);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to mutate a string refernce

A

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
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly