-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
44 lines (38 loc) · 905 Bytes
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package defers
import (
"fmt"
"os"
)
// We previously touched on panics, defer is used to essentially
// guarantee clean up when functions exit (or fail) to avoid things
// like leaking resources etc, similar to pythons context managers.
func Run() {
fileHandle := createFile("foo.txt")
// Instantly defer the closing.
defer closeFile(fileHandle)
writeFile(fileHandle)
fmt.Println("Finished writing data to the file", fileHandle.Name())
}
// Attempt to create a new file.
func createFile(p string) *os.File {
file, err := os.Create(p)
if err != nil {
panic(err)
}
return file
}
// Close the file
func closeFile(f *os.File) {
if err := f.Close(); err != nil {
fmt.Println("Failure closing file", err)
os.Exit(1)
}
}
// Write data to the file
func writeFile(f *os.File) int {
bytes, err := fmt.Fprintln(f, "writing into the file!")
if err != nil {
panic(err)
}
return bytes
}