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

Here's a simple implementation of defer:

#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))))
7 Likes