lifetime-nightmare / src / main.rs
main.rs
Raw
use store::{Product, Store};
use worker::Worker;

mod store;
mod worker;

fn main() {
    let mut store = MyStore {
        product_names: vec![
            String::from("Grapes"),
            String::from("Table"),
            String::from("Pencil"),
        ],
    };

    let worker = Worker::new(&mut store);

    worker.run_with_unsafe(|product| {
        product.set_name(String::from("Banana"));
    });

    for name in store.product_names {
        println!("{name}");
    }
}

struct MyStore {
    product_names: Vec<String>,
}

struct ProductHandler<'a> {
    name: &'a mut String,
}

impl Product for ProductHandler<'_> {
    fn name(&self) -> &str {
        self.name
    }

    fn set_name(&mut self, name: String) {
        *self.name = name;
    }
}

impl Store for MyStore {
    type Product<'this> = ProductHandler<'this>
    where
        Self: 'this;

    fn products<'product, 'iterator: 'product, 'this: 'iterator>(
        &'this mut self,
    ) -> impl store::ProductIterator<Item<'product> = Self::Product<'product>> + 'iterator {
        self.product_names
            .iter_mut()
            .map(|name| ProductHandler { name })
    }
}