Sunday 13 October 2019

Traits in structs.


I am currently aware of 2 ways to handle the fact you can't put a trait in a struct. (Reason: Traits don't have size at compile time)

1) Box the trait
2) Use an enum instead of a trait (enums have a size at compile time).

If you box the trait, you may end up needing to clone it. Cloning a boxed object is possible here is how to do it:

Cut and Paste of the relevant code here:

trait Foo {
    fn box_clone(&self) -> Box<Foo>;
}

impl Clone for Box<Foo>
{
    fn clone(&self) -> Box<Foo> {
        self.box_clone()
    }
}

#[derive(Clone)]
struct Bar;

impl Foo for Bar {
    fn box_clone(&self) -> Box<Foo> {
        Box::new((*self).clone())
    }
}

#[test]
fn it_works() {
    let baz = Box::new(Bar) as Box<Foo>;
    let qux = baz.clone();
}

If using Box across Threads (eg Rayon) you must implement Send & Sync
https://gist.github.com/bootandy/468230baaec80d04fb3a9a9e885e3d5a

No comments:

Post a Comment