Hacker News new | ask | show | jobs
by akiselev 3886 days ago
Rust functions return expressions, not objects and it is entirely up to the compiled code at the function call site whether it is placed in the stack or the heap, and whether the function code is inlined or not (thus expanding the stack allocated in the parent function). ::new doesn't create a structure, it just returns the expression that is supposed to initialize the struct in memory, which the compiler writes to the stack or to the heap through the Box constructor.

If you look at the antipattern example in the "Returning Pointers" section of the Rust book [1], you'll see how you are supposed to handle object creation (the box syntax is the same as Box::new) in a Rustic way

[1] https://doc.rust-lang.org/book/box-syntax-and-patterns.html