<ao> | Adetunji's Blog

More on referencing

You don't pass around ownership with references.

fn main(){
	let my_name = get_name()
}

fn get_name() -> &String{
	let name = "Adetunji".to_string();
	let ref_name = &name;
	ref_name
}

The code above will result in an error and the compiler helps us understand what the error is, in simple terms since a variable will live and die in the block it is defined the String owns it data and it's ownership dies with it. the ref_name pointer at the point of leaving the get_name function will be pointing to an empty memory.

You can also use references to change data, Mutable References It will be mutable reference for mutable variables. When you use mutable reference, you are using a fat pointer its pointing to much data and you will have to unpack it to get to the data itself by De-refrencing it with the * opposite to & used for referencing.

fn main(){
	let num = 2;
	let ref_num = &mut num;

	*ref_num += 4;
	println!("num is now {}", num); // num is now 6
}

Rust Reference Rules

  1. Immutable References: You can have as many immutable references as you want, as you only just viewing data.
  2. Mutable References: You can only have one mutable reference and you can't have a mutable and immutable reference together.

#note #rust