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 variablex
and assigns it the value5
.let y = &x;
: This creates a reference tox
and assigns it toy
.println!("{}", y);
: This prints the value ofx
using the referencey
.x = 6;
: This changes the value ofx
to6
.
Helpful links
Related
More of Rust
- How to compare with null in Rust
- Hashshet example in Rust
- How to parse JSON string in Rust?
- How to convert Rust bytes to a vector of u8?
- How to use an enum in a Rust HashMap?
- How to check if a Rust slice contains a certain value?
- How to split a Rust slice into chunks?
- How to loop with condition in Rust
- How to concatenate Rust slices?
- How do I get the type of a variable in Rust?
See more codes...