rustHow to return borrow in Rust
Returning a borrow in Rust is a process of returning ownership of a borrowed value back to its original owner. This is done by using the return
keyword.
Example:
fn main() {
let mut x = 5;
let y = &mut x;
*y += 1;
println!("x = {}", x);
return y;
}
Output example
x = 6
The code above borrows the value of x
and stores it in y
. The value of x
is then incremented by 1. After that, the ownership of y
is returned to its original owner, x
.
Code explanation
let mut x = 5;
: Declares a mutable variablex
with an initial value of 5.let y = &mut x;
: Borrows the value ofx
and stores it iny
.*y += 1;
: Increments the value ofy
by 1.return y;
: Returns the ownership ofy
back to its original owner,x
.
Helpful links
Related
More of Rust
- How to use non-capturing groups in Rust regex?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to convert a Rust HashMap to JSON?
- How to use regex to match a double quote in Rust?
- How to get an element from a HashSet in Rust?
- How to use look behind in regex in Rust?
- How to use regex lookbehind in Rust?
- How to use a tuple as a key in a Rust HashMap?
- How to match whitespace with a regex in Rust?
See more codes...