rustBorrow example in Rust
A borrow in Rust is when a variable is given temporary access to a resource. This allows the variable to use the resource without taking ownership of it.
let mut x = 5;
let y = &x;
println!("x = {}", x);
println!("y = {}", y);
Output example
x = 5
y = 5
In this example, x is a mutable variable with the value of 5. y is a borrow of x, meaning it has access to the value of x without taking ownership of it. When we print out the values of x and y, we can see that they are both 5.
Code explanation
let mut x = 5;: This declares a mutable variablexwith the value of 5.let y = &x;: This declares a borrow ofxcalledy.println!("x = {}", x);: This prints out the value ofx.println!("y = {}", y);: This prints out the value ofy.
Helpful links
Related
- How borrow instead of move in Rust
- How to borrow with lifetime in Rust
- When to use borrow in Rust
- Example of borrow_mut in Rust
- How to borrow int in Rust
- How to borrow struct field in Rust
- How to borrow hashmap in Rust
- How to disable borrow checker in Rust
- How to return borrow in Rust
- How to borrow moved value in Rust
More of Rust
- How to use regex to match a double quote in Rust?
- How to map a Rust slice?
- How to use regex to match a group in Rust?
- How to perform matrix operations in Rust?
- How to replace strings using Rust regex?
- How to use regex lookbehind in Rust?
- Bitwise operator example in Rust
- Regex example to match multiline string in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
- Pointer arithmetic example in Rust
See more codes...