Go course

Functionsdefer

Go

Display

Theme

Functions · Output exercise

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):

  1. In kirimPesan, the [tutup koneksi] ("close connection") line has to print after the message is sent. Make that line a defer.
  2. In main, the two closing lines have to print at the very end. Make both of them defer — 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
main.go
package main

import "fmt"

func kirimPesan(pengirim, isi string) {
	fmt.Println("[buka koneksi]", pengirim)
	// TODO: jadikan baris berikut defer
	fmt.Println("[tutup koneksi]", pengirim)
	fmt.Printf("%s: %s\n", pengirim, isi)
}

func main() {
	// TODO: jadikan dua baris berikut defer agar dicetak paling akhir
	fmt.Println("Aplikasi ditutup")
	fmt.Println("Menyimpan riwayat chat...")

	fmt.Println("Aplikasi chat dimulai")
	kirimPesan("Andi", "Halo semua!")
	kirimPesan("Maya", "Selamat pagi")
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)