Take a look at the following simple example:
use std::rc::Rc;
struct MyStruct {
a: i8,
}
fn main() {
let mut my_struct = MyStruct { a: 0 };
my_struct.a = 5;
let my_struct_rc = Rc::new(my_struct);
println!("my_struct_rc.a = {}", my_struct_rc.a);
}
The official documentation of Rc
says:
The type
Rc<T>
provides shared ownership of a value of typeT
, allocated in the heap.
Theoretically it is clear. But, firstly my_struct
is not immediately wrapped into Rc
, and secondly MyStruct
is a very simple type. I can see 2 scenarios here.
- When
my_struct
is moved into theRc
the memory content is literally copied from the stack to the heap. - The compiler is able to resolve that
my_struct
will be moved into theRc
, so it puts it on the heap from the beginning.
If number 1 is true, then there might be a hidden performance bottleneck as when reading the code one does not explicitly see memory being copied (I am assuming MyStruct
being much more complex).
If number 2 is true, I wonder whether the compiler is always able to resolve such things. The provided example is very simple, but I can imagine that my_struct
is much more complex and is mutated several times by different functions before being moved to the Rc
.