Borrowing in Rust

Way back in Chapter 2, Variables, we referred to something known as a reference and it was said to be a copy of the pointer to some memory location. This is a big part of what is meant by borrowing in Rust.

In our preceding example, we can make use of borrowing. Our code for it is as follows:

fn sumprod(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 
{ 
    let sum = v1.iter().fold(0i32, |a, &b| a + b); 
    let product = v2.iter().fold(1i32, |a, &b| a * b); 
    return sum + product;  
} 
 
fn main()  
{ 
    let vecone = vec![2,3,5]; 
    let vectwo = vec![3,5];  
    let ans = sumprod(&vecone, &vectwo);  
    println!("ans = {}", ans); 
} 
The code for this section can be found in the 08/handback folder which can be found in the supporting code bundle of this book.

We will no longer pass ownership, but rather we will pass the reference to the vector. When compiled, we will get the following result:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset