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);
}