How to send `Box <dyn SomeTrait>` from parent struct to child?

pub struct DataImporter {
    logger: Box<dyn Logging>,
}

impl DataImporter {
    fn import(&self, origin_type: OriginType, data: String) -> Vec<ResultRow> {
        match origin_type {
            OriginType::SomeCase => {
                let importer = ChildImporter::new(self.logger.into()); // not working
                importer.import(origin_type, data)
            }
            OriginType::OtherCase => {
                let importer = AnotherChildImporter::new(self.logger); // not working either
                importer.import(origin_type, data)
            }
        }
    }
}

pub struct ChildDataImporter {
    logger: Box<dyn Logging>,
}

pub trait Logging: Send + Sync + std::fmt::Debug {
    fn log(&self, level: LogLevel, message: String);
}

We may need to share the Box<dyn Logging> reference. But I'm not sure how to do that.

Use Rc or a reference.

1 Like

You can replace the Box with a Rc or Arc.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.