github.com/hongwozai/go-src-1.4.3@v0.0.0-20191127132709-dc3fce3dbccb/doc/progs/defer2.go (about)

     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