Search code examples
rustallocation

Create empty boxed slice


What is the most canonical way to create Box<[T]> which is empty? Such box should effectively just become a dangling pointer with zero length and nothing should be allocated, right?


Solution

  • What is the most canonical way to create Box<[T]> which is empty?

    Box::from() or slice::into().

    Such box should effectively just become a dangling pointer with zero length and nothing should be allocated, right?

    No. [T] is a slice, which is a DST. In such a case, Box would be a fat pointer, with box itself holding the metadata (the size of the slice):

    let ar = [0;5];
    let boxed: Box<[_]> = ar[..].into();
    println!("{}", std::mem::size_of_val(&boxed));
    

    will print 16, even if the underlying slice is empty (e.g. ar[..0]).

    If the value is a ZST however (e.g. Box<[_;0]>) then there is indeed a special case to not allocate: https://github.com/rust-lang/rust/blob/9c09c1f7cfcf9de0522bcd1cfda32b552195c464/library/alloc/src/alloc.rs#L163