About Box and box

Can I have the syntax at C ? I think it is more elegant :upside_down_face:

trait Trait {}
struct S;
impl Trait for S {}

fn main(){
  let a = Box::new(S) as Box<dyn Trait>;
  let b = box S as Box<dyn Trait>;
  let c = box S as box dyn Trait;          // C

have parser treat box T as a syntax sugar of Box<T> ?

Box is already special cased too much IMO with box expr, box pat and moving *some_box, so please don't introduce yet another special case for it.

What about writing it like this?

let c: Box<dyn Trait> = Box::new(S);

It seems box is introduced after Box (because box is unstable at this moment), so, before its introduction , how the programmer tell compiler to allocate from heap ?

Using Box::new(val). It could be implemented directly using Global.alloc(), but due to the aforementioned special casing of Box combined with legacy reasons it is implemented as box val, which desugars into a call to exchange_malloc followed by a write of the value.

That's actually kind of backwards: box was the "original" way to create a Box<T>ยน, and Box::new was created later when it became clear that box syntax needed some work.

However, Box::new made it into Rust 1.0, and box syntax has just languished for five years, partly because the cases where box syntax is really necessary are few and far between. The global allocator API wasn't stabilized until even later, so if you wanted to allocate from the heap on stable before Rust 1.28, you had to use Box::new (or Vec::new, etc.).

ยน Well, kind of. Box<T> replaced a built-in pointer type called ~T, and there was a special operator ~ to create a ~T. When the switch was made, box replaced ~.


The one case I miss box being special cased is for pattern matching, where you can match on struct S(Box<Option<i32>>) just by writing S(box Some(val)) instead of having to have two match levels.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.