-
Notifications
You must be signed in to change notification settings - Fork 0
/
defer01.go
51 lines (40 loc) · 1.12 KB
/
defer01.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
45
46
47
48
49
50
/* RZFeeser | Alta3 Research
Defer - cleanup operations on file creation */
package main
import (
"fmt"
"os"
)
// expects input, "p" to be a string
// will return os.File object
func createFile(p string) *os.File {
fmt.Println("Creating file...")
f, err := os.Create(p)
if err != nil {
panic(err)
}
return f
}
// exects input, f, to be an os.File object
// returns nothing
func writeFile(f *os.File) {
fmt.Println("Writing employee list to file...")
fmt.Fprintln(f, "Cloud Strife\nAerith Gainsborough\nRed XIII\nVincent Valentine")
}
func closeFile(f *os.File) {
fmt.Println("Closing file...")
err := f.Close()
// best practice says to still check for errors
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func main() {
// create file object
f := createFile("/tmp/employeeList.txt")
// after getting back a file object, we defer closing closeFile()
defer closeFile(f) // closeFile() will be executed at end of the enclosing
// function-- in this case, main()
writeFile(f)
}