rustHow to borrow a variable in Rust
Borrowing a variable in Rust is done using the &
operator. This operator creates a reference to the variable, allowing it to be used without taking ownership of it.
let mut x = 5;
let y = &x;
println!("x = {}", x);
println!("y = {}", y);
Output example
x = 5
y = 5
The code above creates a mutable variable x
and a reference y
to it. The &
operator creates a reference to x
which can be used to access its value without taking ownership of it.
Parts of the code:
let mut x = 5;
: creates a mutable variablex
with the value5
let y = &x;
: creates a referencey
to the variablex
println!("x = {}", x);
: prints the value ofx
println!("y = {}", y);
: prints the value ofy
, which is the same as the value ofx
Helpful links
Related
- How to borrow with lifetime in Rust
- How to borrow a string in Rust
- How to borrow as static in Rust
- When to use borrow in Rust
- How to borrow moved value in Rust
- How to return borrow in Rust
- Rust partial borrow example
- How to borrow in loop in Rust
- How to borrow hashmap in Rust
- How to borrow from vector in Rust
More of Rust
- How to get a capture group using Rust regex?
- How to split a string by regex in Rust?
- How to use regex to match a double quote in Rust?
- How to use regex with bytes in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to use regex lookahead in Rust?
- How to use captures_iter with regex in Rust?
- How to use regex to match a group in Rust?
- How to perform matrix operations in Rust?
- How to declare a matrix in Rust?
See more codes...