Mutable References
Mutable references are created using &mut instead
of & to make the reference. The first variable
must be created with mut too. When we make
modifications to the reference the value
change shows up in the alfa variable too.
The steps for this example are:
- Create a mutable variable named
alfawith aStringbound to it - Print
alfato display the value - Create a variable named
bravothat has a mutable reference toalfa - Update the value in
bravowith.push_str() - Print out
bravoto display its value - Print out
alfaagain to show that the value updated there too
The output of this code is:
alfa has apple
bravo has applepie
alfa has applepie
SOURCE CODE
fn main() {
let mut alfa = String::from("apple");
println!("alfa has {alfa}");
let bravo = &mut alfa;
bravo.push_str("pie");
println!("bravo has {bravo}");
println!("alfa has {alfa}");
}
CODE RUNNER
Typos: 0