fn main(){
let s1 = String::from("Hello");
change_string(&s1);
println!("String is {} ", s1);
}
fn change_string(s1: &String) -> usize {
s1.push_str("World!");
}
Above code will give compilation error
References are IMMATABLE.
Here s1 cannot be modified in change_string function
Simple steps
fn main(){
let mut s1 = String::from("Hello");
change_string(&mut s1);
println!("String is {} ", s1);
}
fn change_string(s1: &mut String) -> &String {
s1.push_str("World!");
s1
}
String is HelloWorld!
Bingo now change_string function will be able to change/mutate value without taking ownership of variable/value
There is a condition to MUTABLE References
- you CANNOT have two variable for MUTABLE references
Example
fn main(){
let mut s1 = String::from("Hello");
let ref1 = &mut s1;
let ref2 = &mut s1; //NOT allowed
println!("{}", ref1);
}
Above code will not compile
If there are two pointer to same data and one of them changed
so there is no mechanism to synchronize that data
That's all for today.
Give our social media a like for latest update on content