where does enum store in,heap or stack?
On stack, usually. Box
, Vec
, Rc
, Mutex
are stored on the heap, most other things are on the stack unless you box them.
I think it's fair to see any enum variant as analogous to a struct
definition.
Consider this enum:
enum Foo {
ZeroSized,
StackTuple(usize),
HeapTuple(usize, String),
StackStruct { field: usize },
HeapStruct { field0: usize, field1: String },
}
In first principle, an enum is light weight and so, like @kornel said, tries to live on the stack when possible.
Thus, Foo::ZeroSized
is fully stored on the stack, as are Foo::StackTuple
and Foo::StackStruct
.
However, Foo::HeapTuple
and Foo::HeapStruct
live partially on the stack (the usize
field and a part of the String
field) and partially on the heap (the other part of the String
field).
Basically, by default anything with a size known at compile-time is by default stored on the stack. The heap is generally for things which can grow, shrink, or otherwise have a size unknowable at compile-time.
jjpe hinted at that fact above by mentioning that some fields of the enum are stored on the stack, whereas some are stored in the heap. Any given enum is always the same size in bytes, even if one of its members is a reference to a growable type. The enum itself, including its reference field, will live on the stack, while the referent will live on the heap.
That said, you can Box
things as mentioned by kornel and put them on the heap anyway. But this wouldn't really serve much of a purpose. Rust encourages keeping things on the stack whenever possible, even things which we pass other functions references to.