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
More of Rust
- How to replace a capture group using Rust regex?
- How to use regex captures in Rust?
- How to use named capture groups in Rust regex?
- How to use regex with bytes in Rust?
- How to use regex to match a double quote in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to match the end of a line in a Rust regex?
- How to parse JSON string in Rust?
- How to convert a Rust slice to a fixed array?
- How to calculate the inverse of a matrix in Rust?
See more codes...