openlang

Delaying a cleanup block's mutable borrow until it actually runs

What would be a way for me to write a panic-safe mecanism in Rust that behaves similarly to Java's try { ... } finally { ... }, where the try and finally blocks each mutably borrow the same value?

What I need is for a try block's borrows to finish as soon as control leaves it, whether by normal execution or panic unwinding, with the finally block borrowing only once control reaches it.

With scopeguard::defer!, the closure has to be declared before the equivalent try block, which starts the mutable borrow immediately upon creating that closure, which means the code corresponding to the try block cannot then take its own mutable borrow of the same thing already borrowed by that closure.

The conversation continues 2

Follow the reasoning
  1. Permalink

    With scopeguard::defer!, the closure has to be declared before the equivalent try block, which starts the mutable borrow immediately upon creating that closure,

    defer!() isn't suitable here, but the guard function can place your value inside a scopeguard::ScopeGuard insted.

    since ScopeGuard supplies Deref and DerefMut, accessing the guard works like accessing the value it holds.

    struct Resource {}
    
    // ownership of the resource goes into this destructor
    // a closure normally serves this purpose
    fn release_resource(resource: Resource) {
        println!("dropping resource");
    }
    
    fn main() {
        // obtain the resource, then give it a guard
        let resource: Resource = acquire_resource();
        let mut resource = guard(resource, release_resource);
        // borrowing the resource mutably is another option
        // let mut resource = guard(&mut resource, release_resource_by_mut);
    
        // access the enclosed resource through its guard
        resource.refresh();
        inspect_resource(&resource);
        change_resource(&mut resource);
    
        // leaving this scope runs the destructor
        // or disable the guard to recover the resource
        // without invoking its destructor
        // let resource = ScopeGuard::into_inner(resource);
    }

Other sides of the same question

  1. Same sink call, a copy on one line and a move on the next

    Nim 2 decides copy or move per call site. Not per proc. Same argument, same proc. The first call copies, because a is still n…

    Replies 2Latest activity nim
  2. Inputting character arrays through pointers

    Whenever I attempt keyboard input into some char arrays, my program ends up crashing. What's a straightforward way of reading…

    Replies 2Latest activity c
  3. Can an input function avoid relying on global variables?

    I'd like a function to process what a user enters, filter it, and return the resulting string to whichever function called it…

    Replies 2Latest activity c