Skip to content

Can ScopeGuards be returned? #13

Closed
@radix

Description

@radix

Hi, I'm not really sure if ScopeGuard does what I'm looking for (or if it's possible at all in Rust).

I can't find any examples of code that returns ScopeGuards without parameterizing the guard closure type.

Imagine I have a collection and I would like to implement a get_mut which returns a mutable reference to an element of the collection. Also imagine that I need to perform some bookkeeping with the element after it's been mutated by user-code. I'd like to return a ScopeGuard wrapped around the element with my own closure that will do that bookkeeping. I haven't been able to figure out how to do this since I can't figure out how to write the ScopeGuard type (but this may just be my lack of experience with Rust).

Here's some example code which wraps a HashMap. I'm not really sure what the heck I'm doing with that second type parameter for ScopeGuard; I got there just by following compiler errors.

  pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> ScopeGuard<Option<&mut V>, for<'r> FnMut(&'r mut Option<&mut V>) -> (), scopeguard::Always>
  where
    <V as DeriveKey>::KeyType: ::std::borrow::Borrow<Q>,
    Q: hash::Hash + Eq,
    { guard(self.data.get_mut(k), |v| ()) }

but this isn't working because rustc is saying that the for<'r> FnMut type is not Sized.

So I'd just like to see if what I'm trying to do is even possible before further banging my head against it :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions