I read in some stack-overflow about Go's GC.
Stack and heap models in Go Garbage collector I want to know that if a variable needs to be defined in heap or stack in Go and then if GC want to collect it, what algorithm is used for this?
If we assume that in languages that have GC that heap is more efficient, but what about Rust and how does rust handle this in compare to Go?
Especially about reference counter in Go that we have no choice in most of times to ask compiler but such a tool exist and it does its job on its own way!
I read this : Stack vs heap allocation of structs in Go, and how they relate to garbage collection
This question is based on wrong assumption that Rust has managed memory. It does not. Besides an allocator, and tools in std that you can use, compiler does not do anything without being asked to.
Rust uses RAII (Resource acquisition is initialization) and unless you specifically create std::rc::Rc<T>
, for example
fn main() {
let my_rc = std::rc::Rc::new(5);
let my_rc_cloned = my_rc.clone();
println!("original: {}, cloned: {}", my_rc, my_rc_cloned);
} // both Rc's are dropped, refcount is 0, and 5 is dropped too
There's no reference counting involved. Ever. Values are pushed and popped off current thread stack like in any low level programming language, such as C.
let rc = Rc::new(value: T);
, creates a new struct, on the stack, C++ uses RAII too, and std::shared_ptr<int> rc(new int(5));
is how you create reference counting pointer in it.
Both rc
's are on the stack and are dropped/destructed once particular block is popped off the stack. That's how RAII works, without going into any minor details.