Rust Onwership
String,&String,str and &str
- String A dynamic piece of text stored on the heap at runtime.
- &String A reference of the String stored on the heap. It is a variable contains the address of the string
- str A hard-coded piece of text embeded in the binary code and it will loaded to the stack memory at runtime. It is part of your banary code.
- &str A reference to a hard coded text in the binary. It holds the address of the str.
The Copy trait and Reference
In Rust, if a type implements copy trait, Rust assignment statement(starting from let keyword) will make a copy of the variable. This is the fundimental rule to follow in Rust. Since referrence type implements copy trait, when you assign a reference to another variable, the variable will store the same address as the original reference variable.
let dog: &str = "My dog's name is occean";
let another_dog: &str = dog;
dog variable holds the address of the string encoded in your binary on stack and another_dog will hold the same address since reference implements copy trait.
Ownership and function parameters
If you think of passing parameters to a function is like that you are assigning the variables with let keyword, then the same rules in Rust is applied in the function parameters. If a type implements the copy trait, then the parameter is a copy of the original variable and there is no ownership transfer.
*Note*
String type does not implements copy trait.
fn perform(value: String) {
}
fn main() {
let my_dog = "The name is Sun";
perform(my_dog) -- ownership transfered to value.
println!("{my_dog}") --- my_dog is not valid any more at this point.
}
Top comments (0)