title: Golang-like defer in Rust
body: <p>In Go, you can use the <code>defer</code> keyword to execute a function when the current function returns, similar to the traditional <code>finally</code> 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:</p>
  
  <pre><code>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)
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>I found <a href="https://gist.github.com/karablin/8568808">this Gist</a> but I don't know if this is a recommended approach. The unsafe destructor is worrisome.</p>
  
  <p>There is also <a href="https://github.com/rust-lang/rust/issues/1523">this issue</a> on the Rust GitHub repository, but it's three years old and clearly not very relevant anymore.</p>