Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang-like defer in Rust

Tags:

go

rust

In Go, you can use the defer keyword to execute a function when the current function returns, similar to the traditional finally keyword in other languages. This is useful for cleaning up state regardless of what happens throughout the function body. Here's an example from the Go blog:

func CopyFile(dstName, srcName string) (written int64, err error) {     src, err := os.Open(srcName)     if err != nil {         return     }     defer src.Close()      dst, err := os.Create(dstName)     if err != nil {         return     }     defer dst.Close()      return io.Copy(dst, src) } 

How can this functionality be achieved in Rust? I know about RAII, but in my specific case the state is in an external system. I'm writing a test that writes a key to a key-value store, and I need to make sure it's deleted at the end of the test regardless of whether or not the assertions in the test cause a panic.

I found this Gist but I don't know if this is a recommended approach. The unsafe destructor is worrisome.

There is also this issue on the Rust GitHub repository, but it's three years old and clearly not very relevant anymore.

like image 447
Jimmy Avatar asked Apr 30 '15 09:04

Jimmy


2 Answers

(e: don't miss bluss's answer and their scopedguard crate, below.)

The correct way to achieve this by having code that runs in a destructor, like the defer! macro you link to does. For anything more than ad-hoc testing I would recommend writing a handle type with a proper destructor, e.g. one interacts with std::sync::Mutex via its MutexGuard type (returned by lock): there's no need to call unlock on the mutex itself. (The explicit handle-with-destructor approach is more flexible too: it has mutable access to the data, whereas the deferred approach may not be able to, due to Rust's strong aliasing controls.)

In any case, that macro is now (much!) improved due to recent changes, in particular, pnkfelix's sound generic drop work, which removes the necessity for #[unsafe_destructor]. The direct update would be:

struct ScopeCall<F: FnMut()> {     c: F } impl<F: FnMut()> Drop for ScopeCall<F> {     fn drop(&mut self) {         (self.c)();     } }  macro_rules! defer {     ($e:expr) => (         let _scope_call = ScopeCall { c: || -> () { $e; } };     ) }  fn main() {     let x = 42u8;     defer!(println!("defer 1"));     defer!({         println!("defer 2");         println!("inside defer {}", x)     });     println!("normal execution {}", x); } 

Output:

normal execution 42 defer 2 inside defer 42 defer 1 

Although, it would be syntactically nicer as:

macro_rules! expr { ($e: expr) => { $e } } // tt hack macro_rules! defer {     ($($data: tt)*) => (         let _scope_call = ScopeCall {              c: || -> () { expr!({ $($data)* }) }         };     ) } 

(The tt hack is necessary due to #5846.)

The use of the generic tt ("token tree") allows one to invoke it without the inner { ... } when there are multiple statements (i.e. it behaves more like a "normal" control flow structure):

defer! {     println!("defer 2");     println!("inside defer {}", x) } 

Also, for maximum flexibility about what the deferred code can do with captured variables, one could use FnOnce instead of FnMut:

struct ScopeCall<F: FnOnce()> {     c: Option<F> } impl<F: FnOnce()> Drop for ScopeCall<F> {     fn drop(&mut self) {         self.c.take().unwrap()()     } } 

That will also require constructing the ScopeCall with a Some around the value for c. The Option dance is required because calling a FnOnce moves ownership, which isn't possible from behind self: &mut ScopeCall<F> without it. (Doing this is OK, since the destructor only executes once.)

All in all:

struct ScopeCall<F: FnOnce()> {     c: Option<F> } impl<F: FnOnce()> Drop for ScopeCall<F> {     fn drop(&mut self) {         self.c.take().unwrap()()     } }  macro_rules! expr { ($e: expr) => { $e } } // tt hack macro_rules! defer {     ($($data: tt)*) => (         let _scope_call = ScopeCall {             c: Some(|| -> () { expr!({ $($data)* }) })         };     ) }  fn main() {     let x = 42u8;     defer!(println!("defer 1"));     defer! {         println!("defer 2");         println!("inside defer {}", x)     }     println!("normal execution {}", x); } 

(Same output as the original.)

like image 134
huon Avatar answered Sep 22 '22 19:09

huon


I use the following for a scope guard. It uses the Deref traits to provide shared & mutable access to the guarded value, without moving it out (that would invalidate the guard!)

My use case is correctly resetting the terminal when the program exits, even if panicking:

extern crate scopeguard; use scopeguard::guard;  // ... terminal setup omitted ...  // Use a scope guard to restore terminal settings on quit/panic let mut tty = guard(tty, |tty| {     // ... I use tty.write() here too ...     ts::tcsetattr(tty.as_raw_fd(), ts::TCSANOW, &old_attr).ok(); }); game_main(&mut tty).unwrap();   // Deref coercion magic hands off the inner &mut TTY pointer here. 

Module scopeguard.rs:

use std::ops::{Deref, DerefMut};  pub struct Guard<T, F> where     F: FnMut(&mut T) {     __dropfn: F,     __value: T, }  pub fn guard<T, F>(v: T, dropfn: F) -> Guard<T, F> where     F: FnMut(&mut T) {     Guard{__value: v, __dropfn: dropfn} }  impl<T, F> Deref for Guard<T, F> where     F: FnMut(&mut T) {     type Target = T;     fn deref(&self) -> &T     {         &self.__value     }  }  impl<T, F> DerefMut for Guard<T, F> where     F: FnMut(&mut T) {     fn deref_mut(&mut self) -> &mut T     {         &mut self.__value     } }  impl<T, F> Drop for Guard<T, F> where     F: FnMut(&mut T) {     fn drop(&mut self) {         (self.__dropfn)(&mut self.__value)     } } 

This is now the crate scopeguard on crates.io.

like image 25
bluss Avatar answered Sep 20 '22 19:09

bluss