<ao> | Adetunji's Blog

Functions can take ownership of data

The ownership concept in Rust is interesting, ownership can be transfer in the course of running a program to an function and the reference to it might be lost if that function isn't spewing it back out.

fn main(){
    let country = String::from("Nigeria");
    say_country(country);
    say_country(country);
}

fn say_country(country_name: String){
    println!("{country_name}")
}

After the first call to the function the data is gone, by the second call you get an error. The compiler rightly points out where the data went and from what point the ownership transferred.

Work around this is:

fn main(){
    let country = String::from("Nigeria");
    let country = say_country(country);
    println!("{country}");
}

fn say_country(country_name: String) -> String{
    println!("{country_name}");
    country_name
}
fn main(){
    let country = String::from("Nigeria");
    say_country(&country);
    say_country(&country);
}

fn say_country(country_name: &String){
    println!("{country_name}")
}

Function can also change data, we can passing in a mutating reference

fn main(){
    let mut country = String::from("Nigeria");
    say_country(&mut country); // prints out Nigeria-Finland
}

fn add_finland(country_name: &mut String){
    country_name.push_str("-FInland");
    println!("{country_name}")
}

We can do this also by letting the function do mutating heavy lifting itself

fn main(){
    let country = String::from("Nigeria");
    update_country(country);
}

fn update_country(mut country_name: String){
    country_name.push_str("-Finland");
    println!("{country_name}")
}

This way there will be no need to declare country in the main function body as a mutable variable.

#note #rust