Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Exercise: Defer remove temporary directory

Write a function that will create a temporary directory and then it will remove it once the function is done. Make sure the directory is removed no matter how you exit from the function.

package main

import "fmt"

func main() {
	doSomething()

}

func doSomething() {
	dir := createTempDir()

	//defer removeTempDir(dir)

	if true {
		removeTempDir(dir)
		return
	}

	removeTempDir(dir)
}

func createTempDir() string {
	return "some/path"
}

func removeTempDir(dir string) {
	fmt.Printf("")
}