#Struct that create instances of T

1 messages · Page 1 of 1 (latest)

tame dawn
#

So my goal here is to have a structure, that can create instance of a template T where T is implementing a specific trait.
Like this:

trait MyTrait {
    fn do_something(&self);
}

Here is my struct that generate the instances, I've put them in a Box because the size can vary

struct MyStruct {
  instances: Vec<Box<dyn MyTrait>>,
}

this struct as a gen function which take a template T that implement MyTrait, it also ask for the Default trait so that he's able to generate a default instance without breaking the Object-safety

impl MyStruct {
  // ...
  pub fn gen<T>(...) -> bool
  where T: MyTrait + Default
  {
    self.instances.push(Box::new(T::default()));
  }
  // ...
}

But this kind of code is throwing an error when doing the push "the parameter type MyTrait may not live long enough"
and I'm very confuse by this error because I'm literally creating the MyTrait instance and putting it in a Box so I would assume that the lifetime was going to be bound to the vector or something.
In my attempt I've tried to add the 'a lifetime to my struct so that the Box lifetime in my vector was bound to the lifetime of the struct, but it ain't working :/
If you wonder why I do this, is because I started to use lambda and that make thing super complicated to interact with other stuff

topaz forum
#

Hmm. Can you show the full output of cargo check?

reef sleet
#

as you may know, the Box<dyn MyTrait> is actually short for Box<dyn MyTrait + 'static>

topaz forum
#

Incidentally, I don't think Default can be implemented for non-'static types anyway. They'd have nowhere to borrow from

reef sleet
#

yes

#

or more strictly speaking, if you can implement Default for a type that's 'a, you can also implement it for the same type that's 'static

topaz forum
#

I guess you can impl<'a> Default for &'a str, right

reef sleet
#

yep

topaz forum
#

The implementation is "", since 'static shortens to 'a

reef sleet
#

so you're not losing an power by restricting to 'static here

tame dawn
#

the compile error did go away when adding + 'static or + 'a (struct lifetime), but I have an access error down the line, may not be caused by this