Understanding of Rust Ownership Part 2

Understanding of Rust Ownership Part 2

How to modify passed value to function and return it?


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

What if we do want to change the referene value ?

Simple steps

  • Make s1 is mutable variable
  • Pass mutable reference to function
  • Function must take mutable reference
  • Function must return mutable reference

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

Why not two mutable references?

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

 

Ejaz Shaikh

I'm passionate about freelancing, technology and healthy lifestyle. I enjoy writing code and writing about code.

Something awesome will come here..