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 variablex
with the value of 5.let y = &x;
: This declares a borrow ofx
calledy
.println!("x = {}", x);
: This prints out the value ofx
.println!("y = {}", y);
: This prints out the value ofy
.
Helpful links
Related
- How to borrow as static in Rust
- How to borrow with lifetime in Rust
- How to borrow a string in Rust
- When to use borrow in Rust
- How to return borrow in Rust
- Rust partial borrow example
- How to borrow moved value in Rust
- How to borrow option value in Rust
- How to borrow in loop in Rust
- How to borrow from vector in Rust
More of Rust
- How to use regex with bytes in Rust?
- How to parse JSON string in Rust?
- How to match whitespace with a regex in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to use a tuple as a key in a Rust HashMap?
- How to replace a capture group using Rust regex?
- How to split a string with Rust regex?
- How to use non-capturing groups in Rust regex?
- How to declare a matrix in Rust?
- How to convert struct to JSON string in Rust?
See more codes...