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 variablexwith an initial value of 5.let y = &mut x;: Borrows the value ofxand stores it iny.*y += 1;: Increments the value ofyby 1.return y;: Returns the ownership ofyback to its original owner,x.
Helpful links
Related
- Rust unsafe borrow example
- How borrow instead of move in Rust
- How to borrow struct field in Rust
- When to use borrow in Rust
- How to borrow moved value in Rust
- How to borrow int in Rust
- How to borrow hashmap in Rust
- How to borrow with lifetime in Rust
- How to borrow from vector in Rust
- How to borrow vector element in Rust
More of Rust
- How to match the end of a line in a Rust regex?
- How to use non-capturing groups in Rust regex?
- Regex example to match multiline string in Rust?
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to use regex lookbehind in Rust?
- How to use regex captures in Rust?
- How to use regex with bytes in Rust?
- How to match whitespace with a regex in Rust?
- How to sort a Rust HashMap?
See more codes...