Giving References to Functions
- we can pass refs to functions both mutable and immutable.
fn print_country(country_name: String) { println!("{}", country_name) } fn main(){ let country = String::from("Austria"); print_country(country); // Value moved here. the function now own the data. The data will be removed once the fuc dies. print_country(country); // πError value used after move. the data does not exist anymore! }
We can solve this problem by passing a ref to the function
fn print_country(country_name: &String) { println!("{}", country_name) } fn main(){ let country = String::from("Austria"); print_country(&country); // βοΈ the func will not take ownership print_country(&country); // βοΈ println!("{}",country); // βοΈ }
example for passing mutable ref
fn add_and_print_hungary(country_name: &mut String){ country_name.push_str("-Hungry"); println!("Now it says: {}" , country_name); } fn main() { let mut country = String::from("Austria"); add_and_print_hungary(&mut country); }