The simplest Rust Types
The simplest rust type are known as Copy
types. They are all on the stack
as the compiler is aware of their sizes.
The compiler always copies their data when you send this types to functions.
We won't have the ownership transfer brouhaha as we did here [[Functions can take ownership of data]]
Types such as Ints
, Floats
, Char
, Booleans
etc are copy types
fn main(){
let age: i32 = 30;
say_age(age)
say_age(age)
}
fn say_age(my_age: i32){
println!("{my_age}")
}
Here, on the second call of say_age()
it works just fine. because a copy of age
was passed to the function and so age
still retains ownership of it's data.
Strings are Clone
types instead and we could as well pass clones of string to achieve same but we need to call .clone()
explicitly.
So copy
is implicit while clone
is explicit
fn main(){
let country = String::from("Nigeria");
say_country(country.clone());
say_country(country)
}
fn say_country(country_name: String){
println!("{country_name}")
}
Ownership is only passed to the function on the second call of say_country()
As a rule: "Pass immutable references to functions if you can".