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 variablexwith the value5let y = &mut x;: creates a mutable referenceyto the variablex*y += 1;: dereferences the referenceyand modifies the value ofxprintln!("x = {}", x);: prints the value ofx
Helpful links
Related
- When to use borrow in Rust
- How to borrow struct field in Rust
- How to borrow hashmap in Rust
- How to return borrow in Rust
- How to borrow with lifetime in Rust
- How to borrow int in Rust
- How to borrow vector element in Rust
- How to borrow moved value in Rust
- Rust unsafe borrow example
- Rust partial borrow example
More of Rust
- How to match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- How to use regex lookahead in Rust?
- How to match a URL with a regex in Rust?
- Bitwise OR operator usage in Rust
- How to use non-capturing groups in Rust regex?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to replace all matches using Rust regex?
- How to use regex lookbehind in Rust?
See more codes...