~ubuntu-branches/ubuntu/utopic/gccgo-go/utopic

« back to all changes in this revision

Viewing changes to doc/progs/defer2.go

  • Committer: Package Import Robot
  • Author(s): James Page
  • Date: 2014-01-27 09:18:55 UTC
  • Revision ID: package-import@ubuntu.com-20140127091855-zxfshmykfsyyw4b2
Tags: upstream-1.2
ImportĀ upstreamĀ versionĀ 1.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// cmpout
 
2
 
 
3
// Copyright 2011 The Go Authors. All rights reserved.
 
4
// Use of this source code is governed by a BSD-style
 
5
// license that can be found in the LICENSE file.
 
6
 
 
7
// This file contains the code snippets included in "Defer, Panic, and Recover."
 
8
 
 
9
package main
 
10
 
 
11
import "fmt"
 
12
import "io" // OMIT
 
13
import "os" // OMIT
 
14
 
 
15
func main() {
 
16
        f()
 
17
        fmt.Println("Returned normally from f.")
 
18
}
 
19
 
 
20
func f() {
 
21
        defer func() {
 
22
                if r := recover(); r != nil {
 
23
                        fmt.Println("Recovered in f", r)
 
24
                }
 
25
        }()
 
26
        fmt.Println("Calling g.")
 
27
        g(0)
 
28
        fmt.Println("Returned normally from g.")
 
29
}
 
30
 
 
31
func g(i int) {
 
32
        if i > 3 {
 
33
                fmt.Println("Panicking!")
 
34
                panic(fmt.Sprintf("%v", i))
 
35
        }
 
36
        defer fmt.Println("Defer in g", i)
 
37
        fmt.Println("Printing in g", i)
 
38
        g(i + 1)
 
39
}
 
40
 
 
41
// STOP OMIT
 
42
 
 
43
// Revised version.
 
44
func CopyFile(dstName, srcName string) (written int64, err error) {
 
45
        src, err := os.Open(srcName)
 
46
        if err != nil {
 
47
                return
 
48
        }
 
49
        defer src.Close()
 
50
 
 
51
        dst, err := os.Create(dstName)
 
52
        if err != nil {
 
53
                return
 
54
        }
 
55
        defer dst.Close()
 
56
 
 
57
        return io.Copy(dst, src)
 
58
}
 
59
 
 
60
// STOP OMIT