matklad / once_cell

Rust library for single assignment cells and lazy statics without macros

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`set()` should return Result<&T, T>, not Result<(), T>

jyn514 opened this issue · comments

commented

Say I want to write a function like this:

    pub(crate) fn override_frontend(&self, init: impl FnOnce(&mut TestFrontend)) -> &TestFrontend { /* ... */ }

Here's the current approach I have to use:

        let mut frontend = TestFrontend::new(&*self);
        init(&mut frontend);
        if self.frontend.set(frontend).is_err() {
            panic!("cannot call override_frontend after frontend is initialized");
        }
        self.frontend.get().unwrap()

It would be nice to be able to remove the second unwrap:

        let mut frontend = TestFrontend::new(&*self);
        init(&mut frontend);
        match self.frontend.set(frontend) {
            Ok(f) => f,
            Err(e) => panic!("cannot call override_frontend after frontend is initialized"),
        }

but right now set() doesn't return that data, so I can't.

The fully general signature would be Resut<&T, (&T, T)>. I think we should add this as an extra method (insert perhaps?).

Ok, naming is hard. We have Option::insert and Option::get_or_insert, which do different things. I think OnceCell::try_insert would probably be the right name for semantics we want here.

try_insert now exists