0
votes

I am very new to rust and currently trying out simple concepts to understand it more. I have created a sample of a Concrete Factory taking a Trait Dependency and its create method returning a Concrete Instance which is defined by a trait.

I am getting errors about lifetime borrowing.

I have create a failing example in the playground here.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f9753708dc202c27101442952dabf560

1

1 Answers

1
votes

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