rustHow to borrow as static in Rust
Static borrowing in Rust is a way to borrow a value without taking ownership of it. This allows the value to be used without having to move it.
let mut x = 5;
{
let y = &x; // y is a reference to x
println!("{}", y);
}
x = 6;
Output example
5
The code above shows an example of static borrowing. The variable x is declared as mutable and assigned the value 5. A reference to x is then created and assigned to y. The reference y is then used to print the value of x. Finally, the value of x is changed to 6.
The parts of the code are:
let mut x = 5;: This declares a mutable variablexand assigns it the value5.let y = &x;: This creates a reference toxand assigns it toy.println!("{}", y);: This prints the value ofxusing the referencey.x = 6;: This changes the value ofxto6.
Helpful links
Related
- How borrow instead of move in Rust
- How to borrow from vector in Rust
- When to use borrow in Rust
- How to borrow with lifetime in Rust
- How to borrow int in Rust
- How to borrow hashmap in Rust
- How to borrow vector element in Rust
- How to return borrow in Rust
- Rust unsafe borrow example
- How to borrow moved value in Rust
More of Rust
- How to use non-capturing groups in Rust regex?
- How to replace a capture group using Rust regex?
- How to print a Rust HashMap?
- How to replace strings using Rust regex?
- Regex example to match multiline string in Rust?
- How to use regex lookbehind in Rust?
- How to match the end of a line in a Rust regex?
- How to create a HashSet from a Range in Rust?
- How to lock a Rust HashMap?
- How to sort the keys in a Rust HashMap?
See more codes...