Search code examples
memoryruststackheap-memoryallocation

How to determine when new() in Rust allocates on stack or heap


Is there a way (except looking at implementation and docs) to determine when new() in rust allocates on stack or heap?

Ideally I'm looking for a way to determine this when writing source at a glance. For example trait or parameter that can be added restricting whether heap allocation can take place.


Solution

  • Functions named new() in Rust are not special in anayway. So no, you cannot easily determine if something returned by such a function owns any heap-allocated data. Even for std::default::Default trait implementations there is no restriction nor convention which prevents the default() method from doing heap allocations, nor is it usually documented.