borrowing in Rust explained with examples

In Rust, borrowing is the mechanism by which you can use a reference to a value stored in one place, but borrow it and use it in another place. Borrowing allows you to use a value without taking ownership of it, which means that you can use the value, but you don’t have the right to modify or destroy it.

There are two types of borrows in Rust: &T, which is an immutable borrow, and &mut T, which is a mutable borrow. An immutable borrow allows you to read the value, but not write to it, while a mutable borrow allows you to both read and write the value.

Here’s an example of borrowing in Rust:

fn main() {
    let s = String::from("hello");

    let len = calculate_length(&s);

    println!("The length of '{}' is {}.", s, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

In this example, we have a function calculate_length that takes a borrow to a String. The function reads the length of the String, but it does not have the ability to modify or destroy the String.

Borrowing is an important concept in Rust because it allows you to use values in different contexts without taking ownership of them. This can be useful when you want to use a value in multiple places, or when you want to pass a value to a function that needs to use it, but should not have the right to modify or destroy it.

Here are some examples of borrowing in Rust:

  1. Immutable borrow:
  2. fn main() {
        let s = String::from("hello");
    
        let len = calculate_length(&s);
    
        println!("The length of '{}' is {}.", s, len);
    }
    
    fn calculate_length(s: &String) -> usize {
        s.len()
    }

    In this example, calculate_length takes an immutable borrow to a String. The function can read the length of the String, but it does not have the ability to modify or destroy the String.

    1. Mutable borrow:
    fn main() {
        let mut s = String::from("hello");
    
        change(&mut s);
    
        println!("{}", s);
    }
    
    fn change(s: &mut String) {
        s.push_str(", world!");
    }

    In this example, change takes a mutable borrow to a String. The function can both read and write to the String.

    1. Borrowing in a loop:

 

fn main() {
    let mut s = String::from("hello");

    for c in s.chars() {
        println!("{}", c);
    }
}

In this example, the for loop takes an immutable borrow to the String. The loop can read the characters of the String, but it does not have the ability to modify or destroy the String.

 

Leave a Reply

Your email address will not be published. Required fields are marked *