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 variablexwith the value5let y = &x;: creates a referenceyto the variablexprintln!("x = {}", x);: prints the value ofxprintln!("y = {}", y);: prints the value ofy, which is the same as the value ofx
Helpful links
Related
- How borrow instead of move in Rust
- How to borrow with lifetime in Rust
- When to use borrow in Rust
- How to borrow struct field in Rust
- How to borrow int in Rust
- How to borrow hashmap in Rust
- How to disable borrow checker in Rust
- How to borrow vector element in Rust
- How to return borrow in Rust
- How to borrow moved value in Rust
More of Rust
- How to replace strings using Rust regex?
- How to use captures_iter with regex in Rust?
- How to use regex to match a double quote in Rust?
- How to use regex lookbehind in Rust?
- How to convert struct to bytes in Rust
- How to use 'or' in Rust regex?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to print a Rust HashMap?
- How to loop through a Rust HashMap?
- How to compare two Rust HashMaps?
See more codes...