Borrowing

Let consider the program in the Chapter "Ownership" :

struct Person 
{
    name : String,
    age : i32
}

fn main()
{
    let p1 = Person {name : "Person 1".to_owned(), age : 10};
    let p2 = p1;
    // Uncomment the following line causes a compilation error
    // println!("{} , {} years old", p1.name, p1.age);
    println!("{} , {} years old", p2.name, p2.age);    
}

The commented line causes a compilation error because after the assign operator, p1 becomes invalid (no longer owns the object). In case we want to use several variables to access to a same object, we need to use references, which is equivalent to pointers in C/C++ :

struct Person 
{
    name : String,
    age : i32
}

fn main()
{
    let p1 = Person {name : "Person 1".to_owned(), age : 10};
    let p2 = &p1;
    println!("{} , {} years old", p1.name, p1.age);
    println!("{} , {} years old", p2.name, p2.age);    
}

The operator & is to create a reference an object. It is equivalent to operator & in C/C++ to get a pointer to an object. In the above example, we say p1 is borrowed by p2. In Rust there are immutable and mutable objects, therefore there are also immutable and mutable borrowing. The & operator is for immutable borrowing and &mut is for mutable borrowing. Of course, you can only get a mutable borrowing for mutable variables.

results matching ""

    No results matching ""