Let me try to explain my question since I am trying to get my foundations on ownership strong.
Datatypes like i32, u8 and &str are stored on the stack since their sizes are known during compile time.
So we can do deep copy operations like the following without any errors.
let num1 :i32= 2;
let _num2 = num1;
println!("Num1 : {}",num1);
let slice1 = "Possible";
let _slice2 = slice1;
println!("Slice 1 : {}",slice1);
But for datatypes that are stored on heap, I understand that we need to give references.
And I also understand that we can't have 2 or more references, if one is a mutable reference.
So copy operations for something like string should be like:
let string1 = String::from("Hello");
let _string2 = &string1;
println!("string : {}",string1);
Okay, but what I don't understand is why does the same rule apply for enums and structs ? Aren't they stored on the stack?
Here is an example of struct
struct Point {
x: i32,
y: i32,
}
let point1 = Point{
x: 12,
y:23,
};
let _point2 = &point1; // Why do I have to create a & reference here?
println!("Point 1 : ({},{})",point1.x,point1.y);
My question beingwhy can't I copy the value just as how other datatypes like i32, &str or u8 would do?
Similarly for enum
enum Mark {
Cross,
Peace,
Love,
}
let marker1 = Mark::Cross;
let _marker2 = &marker1; // Why do I have to create a & reference here?
println!("Marker 1 : {:?}",marker1);
Same question : why can't I copy the value just as how other datatypes like i32, &str or u8 would do?