How do you actually use dynamically sized types in Rust?

前端 未结 3 1420
我寻月下人不归
我寻月下人不归 2020-11-30 10:13

In theory, Dynamically-Sized Types (DST) have landed and we should now be able to use dynamically sized type instances. Practically speaking, I can neither make it work, nor

3条回答
  •  春和景丽
    2020-11-30 10:29

    At the moment, to create a HasFoo storing a type-erased Foo you need to first create one with a fixed concrete type and then coerce a pointer to it to the DST form, that is

    let has_too: &HasFoo = &HasFoo { f: Bar };
    

    Calling has_foo.f.foo() then does what you expect.

    In future these DST casts will almost certainly be possible with as, but for the moment coercion via an explicit type hint is required.

提交回复
热议问题