Is box
just syntactic sugar or can it be applied to use cases where Box::new
is not sufficient? I read somewhere that box
is unstable, does that mean I can only use it with the nightly Rust versions?
相关问题
- Share Arc between closures
- Function references: expected bound lifetime param
- Pattern matching on slices
- How can I iteratively call Sha256::digest, passing
- Destructure a vector into variables and give away
相关文章
- How can I convert a f64 to f32 and get the closest
- What is a good way of cleaning up after a unit tes
- How can I unpack (destructure) elements from a vec
- How to import macros in Rust?
- How to get struct field names in Rust? [duplicate]
- Confusion between [T] and &[T]
- How do I initialize an opaque C struct when using
- What's the most idiomatic way to test two Opti
Box::new
is just a function, like any other function. It is not special in any way whatsoever. It is grubby and smells faintly of very-close-to-the-expiration date cheese.box
is magic and made up ground-up pixies and the dreams of little children. It is dressed in the finest, swankiest clothes and carries with it the faint aroma of freshly cut pine.When you execute
Box::new(e)
, because it is a function,e
must be completely evaluated and constructed before it can start the call. If this means allocating and filling a 500kB structure on the stack, then it has to allocate and fill a 500kB structure on the stack, and then pass that toBox::new
, which only then can allocate the space on the heap (which might fail), and then copy that 500kB into the heap.When you execute
box e
, because it is wonderful like a cool breeze on a hot summer's day, the compiler can reorder things such that it begins by allocating the 500kB on the heap, and then filling the 500kB structure directly on the heap. And then it's done. No extra copying, no chewing through stack space. No wasted effort if that "allocate on the heap" thing fails to work out.box
is life,box
is love; all hailbox
!(And yes, as of writing, it's still unstable which means you need a nightly compiler to bask in its radiance. But soon, the dawn will come. Get it? Dawn? Nightly? ... I'll show myself out...)