You did most things correct, there is only one major constraint you missed: When you return your dyn SomethingToUse
from the factory:
pub fn create(&self) -> Result<Box<dyn SomethingToUse>>{
let something = SomethingConcrete{
helper: self.helper // I removed the & here. That would be a double reference.
};
return Ok(Box::new(something));
}
It contains a reference which is valid for 'a
. You however did not annotate that. The way to do that is dyn SomethingToUse + 'a
.
I also replaced your boxed trait object with an impl SomethingToUse
as I would prefer that in most situations, that's not necessary though.
Link to working code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b02c4ff9d5e2ad03b7dfd2db00941b7c