-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefer.go
54 lines (45 loc) · 984 Bytes
/
defer.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
51
52
53
54
//
// gobyexample.com
// defer.go
//
package main
import (
"fmt"
"os"
)
func main() {
// Suppose we wanted to create a file, write to it,
// and then close when we’re done.
//
// Here’s how we could do that with defer.
f := createFile("/tmp/defer.txt")
defer closeFile(f)
writeFile(f)
}
// Immediately after getting a file object with createFile,
// we defer the closing of that file with closeFile.
//
// This will be executed at the end of the enclosing function (main),
// after writeFile has finished.
func createFile(p string) *os.File {
fmt.Println("creating")
f, err := os.Create(p)
if err != nil {
panic(err)
}
return f
}
func writeFile(f *os.File) {
fmt.Println("writing")
fmt.Fprintln(f, "data")
}
// It’s important to check for errors when closing a file,
// even in a deferred function.
func closeFile(f *os.File) {
fmt.Println("closing")
err := f.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}