github.com/yukk001/go1.10.8@v0.0.0-20190813125351-6df2d3982e20/doc/progs/defer2.go (about)

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