Creating an array of size 0 consumes value, forgetting it

Viewed 466

I stumbled upon this question, and having read ramslök's comment on the accepted answer, I tried it out with a type that was not Copy.

To my surprise it compiled successfully, but it's destructor never ran, effectively forgetting the value, as if std::mem::forget was called. Here is a code example (Playground):

#[derive(PartialEq, Debug)]
struct A;

impl Drop for A {
    fn drop(&mut self) {
        println!("Dropping A");
    }
}

fn main() {
    let vec: Vec<A> = vec![];
    let a = A;
    assert_eq!(vec, [a; 0]);
}

If we tried to use a after the assert_eq, it complains the value was moved into the array.

Forgetting values is already possible via the std::mem::forget, and it does not cause U.B., but it still feels weird that it's possible without compiler magic.

My question is: Is this a bug, or is it an intended feature of rust?

1 Answers

It is a bug, [a; 0] is intended to evaluate and drop a, as described in Rust's docs for the array type:

Note that [expr; 0] is allowed, and produces an empty array. This will still evaluate expr, however, and immediately drop the resulting value, so be mindful of side effects.

Related