Primitive Types and Complex Types
behave differently
Primitive Types and Complex Types
Primitive types behave completely differently from complex types in rust. Take for the instance below.
This is VALID
//Primitive types integers
let y = 5;
let x = y;
println!("{} {}", x, y);
However this is INVALID
//Complex type String
let my_str = String::from("hello world");
let another_str = my_str;
println!("{} {}", my_str, another_str);
So what's happening here?
In the first code since Primitive types are stored on stack, compiler knows the size and hence value 5 is copied into x variable when let x = y
is done. This implements Copy trait ( think of trait as an interface which is present in most high level languages)
However, in case of Complex Types, they are stored on heap. The actual memory is allocated on heap(but the reference to the allocated memory is stored on stack).
let another_str = my_str;
So rust compiler doesn't know about the memory size while compiling hence when above assignment is done, ownership is transferred from my_str
to another_str
. So we cannot use my_str
in the println!
statement :)
Last updated
Was this helpful?