Skip to content

Immutable References

Daniel Cortes edited this page Jul 30, 2024 · 4 revisions

The borrow system creates references to a value, these references allows us to refer to a value without moving it to a new owner inside our codebase.

Anytime you want to make a value and use it in several different locations, passing it as a function argument or referring to it in a struct or anything like that, so changing the ownership is tedious, so a good solution is to use a reference where we use the ampersand operator which has slightly different behavior depending upon where you use it in the codebase.

So in the below diagram we actually make use of the ampersand operator in two different locations and depending upon where you put it, it will have slightly different behavior. So here is the rule: Anytime you put the operator next to a type, it means to Rust that we want it to be a reference to a value, so we are customizing the argument. We also can use the ampersand next to a value or rather an owner of a value because technically in this case let account_ref = &account; is the owner of a value, but thats just being precise. So thats telling Rust we want to create a reference to a value. That line of code is not necessary, I just added it to be precise and make it super clear to me and newbies what is going on. In real Rust code you will just see print_account(&account);, its rare to create a separate reference and assign it to a variable.

fn main() {
    let account = Account::new(1, String::from("me"));

    let account_ref1 = &account;
    let account_ref2 = &account;

    let other_account = account;

    print_account(account_ref1);
    print_account(account_ref2);

    println!("{:#?}", account);
}

We now have Account value and we are assinging it to account binding.

Account reference one and two both look at the account binding. We then try to move Account value to the print_account functions and when called they are looking at account binding but there is NO VALUE there. This is why we cannot move a value while references to a value exist.