x
 
1
// _Defer_ is used to ensure that a function call is
2
// performed later in a program's execution, usually for
3
// purposes of cleanup. `defer` is often used where e.g.
4
// `ensure` and `finally` would be used in other languages.
5
6
package main
7
8
import "fmt"
9
import "os"
10
11
// Suppose we wanted to create a file, write to it,
12
// and then close when we're done. Here's how we could
13
// do that with `defer`.
14
func main() {
15
16
    // Immediately after getting a file object with
17
    // `createFile`, we defer the closing of that file
18
    // with `closeFile`. This will be executed at the end
19
    // of the enclosing function (`main`), after
20
    // `writeFile` has finished.
21
    f := createFile("/tmp/defer.txt")
22
    defer closeFile(f)
23
    writeFile(f)
24
}
25
26
func createFile(p string) *os.File {
27
    fmt.Println("creating")
28
    f, err := os.Create(p)
29
    if err != nil {
30
        panic(err)
31
    }
32
    return f
33
}
34
35
func writeFile(f *os.File) {
36
    fmt.Println("writing")
37
    fmt.Fprintln(f, "data")
38
39
}
40
41
func closeFile(f *os.File) {
42
    fmt.Println("closing")
43
    f.Close()
44
}
45
分享