0

Consider the following code:

trait Consume {
    fn consume(self);
}

struct Foo;

impl Consume for Foo {
    fn consume(self) {}
}

fn main() {
    let mut f = Box::new(Foo {}) as Box<dyn Consume>;
    f.consume();
}

The purpose of having this definition of Consume is as follows:

  1. to allow the consume method to move out of the struct fields; and
  2. to ensure that consume is only ever run once.

There is a technical error in the code above, though, as of version 1.67.0 and edition 2021:

error[E0161]: cannot move a value of type `dyn Consume`
  --> src/bin/consuming_self_in_traits.rs:12:5
   |
12 |     f.consume();
   |     ^^^^^^^^^^^ the size of `dyn Consume` cannot be statically determined

My expectation is that if the compiler is able to generate a Consume vtable for Foo, it must also be able to achieve similar semantics.

Can the code above be compiled without changing the definition of Consume and still using dynamic dispatch on Foo? I do not mind using unsafe.

Mike Land
  • 436
  • 4
  • 15

0 Answers0