Deviopath › Go

Defer Order

Medium · Control Flow

defer runs a call after the surrounding function returns, last-in first-out: the last deferred call runs first. Use a **named result** (out []string) so deferred appends still update the returned slice.

Write Trace(tag) that appends tag+"a", defers tag+"d1", appends tag+"b", defers tag+"d2", then appends tag+"c". Trace("") returns []string{"a", "b", "c", "d2", "d1"}.

Next: Anagrams