skip to content
Alvin Lucillo

Idiomatically close files in Go

/ 1 min read

💻 Tech

It’s important to close the open files because there’s a limit on the number of files a system can have. ulimit -a will show the limit of the system, and one of the limits, file descriptors, shows the maximum number of file descriptors that a user can have open at the same time. In Go, the idiomatic way to close files is to use the defer state right after checking for errors.

func main() {
	// Open the gzip file
	gzipFile, err := os.Open("file.gz")
	// Return if there's an error
	if err != nil {
		fmt.Println(err)
		return
	}
	// Release acquired resources
	defer gzipFile.Close()
}