# How to best implement something like "defer"' in Go?

**URL:** <https://racket.discourse.group/t/how-to-best-implement-something-like-defer-in-go/723>\
**Category:** Questions & Answers\
**Tags:** question, macro\
**Created:** [February 23, 2022, 11:33pm UTC](https://racket.discourse.group/t/how-to-best-implement-something-like-defer-in-go/723 "2022-02-23T23:33:49Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![samth](https://yyz2.discourse-cdn.com/free1/user_avatar/racket.discourse.group/samth/32/3_2.png) [@samth](https://racket.discourse.group/u/samth)\
**Post date:** [February 24, 2022, 2:48pm UTC](https://racket.discourse.group/t/how-to-best-implement-something-like-defer-in-go/723/7 "2022-02-24T14:48:59Z")

</div>

Here's a simple implementation of `defer`:

```scheme
#lang racket

(define x null)

(define-syntax-rule (with-defer e ...)
  (dynamic-wind
    (lambda () (set! x null))
    (lambda () e ...)
    (lambda () (for-each (lambda (i) (i)) x))))

(define-syntax-rule (defer e)
  (set! x (cons (lambda () e) x)))

(with-defer
  (define f (open-input-file "/dev/random"))
  (defer (close-input-port f))
  (displayln (bytes->list (read-bytes-line f))))

```

---

_[View the full topic](https://racket.discourse.group/t/how-to-best-implement-something-like-defer-in-go/723)._
