Rust, Software Development

Rust – Mutable and Shared Borrowing

There are two types of borrowing in Rust – mutable and shared borrowing – and they involve references.

Rust Mutable Borrowing

Using sample codes, Mutable Borrowing in Rust means the owner passes the variable’s ownership to a function but making the variable open to value change. The function definition must specify the parameter with &mut before the type. For instance, line 1 has this parameter definition – v: &mut i32. On the other hand, codes that call the function must provide a mutable variable using the &mut specified before the variable name.

Example 1 – Modify Integer Value

This example outputs the following.

Example 2 – Modify Vect Contents

This outputs

Rust Shared Borrowing

Also using sample codes, Shared Borrowing in Rust means the owner passes a copy of the variable’s value to a function. Therefore, any changes to the function parameter within the function does not change the original variable. The function definition must specify the parameter with & prefixed to the type. For instance, line 1 has this parameter definition – v: &i32. However, codes that call the function must only provide a variable name.

Example 3 – Share Integer Value

This outputs

Understanding Ownership

The concept of ownership and how it works is central to these examples for Shared and Mutable borrowing in Rust. For more information, please see Understanding Ownership.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like