rustHow to borrow as mutable in Rust
Mutable borrowing in Rust is done using the &mut
reference type. This type of reference allows you to modify the data that it points to.
Example:
let mut x = 5;
let y = &mut x;
*y += 1;
println!("x = {}", x);
Output example
x = 6
The code above creates a mutable reference y
to the variable x
. The *
operator is used to dereference the reference y
and modify the value of x
.
Code explanation
let mut x = 5;
: creates a mutable variablex
with the value5
let y = &mut x;
: creates a mutable referencey
to the variablex
*y += 1;
: dereferences the referencey
and modifies the value ofx
println!("x = {}", x);
: prints the value ofx
Helpful links
Related
- How to borrow with lifetime in Rust
- When to use borrow in Rust
- How to borrow moved value in Rust
- How to borrow int in Rust
- How to borrow iterator in Rust
- How to borrow hashmap in Rust
- How to borrow struct field in Rust
- How to borrow a string in Rust
- How to borrow vector element in Rust
- How to return borrow in Rust
More of Rust
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to replace strings using Rust regex?
- How to compare two Rust HashMaps?
- How to use regex captures in Rust?
- How to create a HashSet from a String in Rust?
- How to remove an element from a Rust HashMap if a condition is met?
- Example of yield_now in Rust?
- How to push an element to a Rust slice?
- How to replace a capture group using Rust regex?
See more codes...