defer
A defer statement postpones a function call until the surrounding function finishes (whether through a normal return or by reaching the end of its block).
func main() {
defer fmt.Println("dunia")
fmt.Println("halo")
}
// halo
// dunia
What's it for?
defer is usually used to clean up resources — closing a file, closing a connection, releasing a lock — right after the resource is opened. That way you can't forget to clean up, no matter how many returns the function has:
func bacaLaporan() {
fmt.Println("buka file")
defer fmt.Println("tutup file") // pasti dijalankan saat fungsi selesai
if terjadiMasalah {
return // "tutup file" tetap dicetak
}
fmt.Println("baca isi file")
}
Here "tutup file" ("close file") is guaranteed to print when the function ends — even on the early return.
Order: last in, first out
When there are several defers, they run in reverse order (LIFO — last in, first out), like a stack of plates:
defer fmt.Println("1")
defer fmt.Println("2")
defer fmt.Println("3")
// mencetak: 3, 2, 1
This prints 3, 2, 1.
Arguments are evaluated right away
The arguments of a deferred function call are evaluated when the defer line runs, not when the function finally gets called:
x := 1
defer fmt.Println("x =", x) // mencetak x = 1
x = 99
This prints x = 1, not x = 99.
Task
The chat app program in the editor prints things in the wrong order. Fix it with defer (don't just move the lines around):
- In
kirimPesan, the[tutup koneksi]("close connection") line has to print after the message is sent. Make that line adefer. - In
main, the two closing lines have to print at the very end. Make both of themdefer— watch the LIFO order!
Expected output:
Aplikasi chat dimulai
[buka koneksi] Andi
Andi: Halo semua!
[tutup koneksi] Andi
[buka koneksi] Maya
Maya: Selamat pagi
[tutup koneksi] Maya
Menyimpan riwayat chat...
Aplikasi ditutup