We are going to cover COPY trait , move and references in practical and simple way
Let's get STARTED
fn main(){
let x = 1;
let y = x; //Copy
println!("Value of x {}", x);
}
Value of x 1
Above will work properly
Bingo! Rust implements COPY trait for simple data types stored on STACK such
bool
int
chars
Let's make it little tricky
fn main(){
let s1 = String::from("Hello");
let s2 = s1; //It is not shallow copy, MOVE
println!("{0}", s1);
}
Above s1 is moved to s2 , ownership has moved to s2.
s1 no longer holds the value as "Hello"
So println! will give compilation error
Consider ownership like KING
And king can be only ONE and ownership(throne) can be moved to another KING
What if we actually want to clone/copy String like above variable ?
Simply we can use clone() method as simple as that.
fn main(){
let s1 = String::from("Hello");
let s2 = s1.clone(); //It is not shallow copy, MOVE
println!("{}", s1);
}
Hello
Let's DEEP DIVE little
fn main(){
let s1 = String::from("Hello");
let s2 = calculate_length(s1);
println!("String is {} and length {}", s1, s2); //Will give compile error
}
fn calculate_length(s1: String) -> usize {
s1.len()
}
Code will not compile
Here s1 ownership is moved to function and function return
the ownership to s2
So s1 no longer holds ownership or value
fn main(){
let s1 = String::from("Hello");
let s2 = calculate_length(&s1);
println!("String is {} and length {}", s1, s2);
}
fn calculate_length(s1: &String) -> usize {
s1.len()
}
String is Hello and length 5
Passing value to functions known as Borrowing
You are borrowing value not the OWNERSHIP
That's it for this blog
You will learn more about ownership in next one
Stay tune!