defer.go 860 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. // This file contains the code snippets included in "Defer, Panic, and Recover."
  5. package main
  6. import (
  7. "fmt"
  8. "io"
  9. "os"
  10. )
  11. func a() {
  12. i := 0
  13. defer fmt.Println(i)
  14. i++
  15. return
  16. }
  17. // STOP OMIT
  18. func b() {
  19. for i := 0; i < 4; i++ {
  20. defer fmt.Print(i)
  21. }
  22. }
  23. // STOP OMIT
  24. func c() (i int) {
  25. defer func() { i++ }()
  26. return 1
  27. }
  28. // STOP OMIT
  29. // Initial version.
  30. func CopyFile(dstName, srcName string) (written int64, err error) {
  31. src, err := os.Open(srcName)
  32. if err != nil {
  33. return
  34. }
  35. dst, err := os.Create(dstName)
  36. if err != nil {
  37. return
  38. }
  39. written, err = io.Copy(dst, src)
  40. dst.Close()
  41. src.Close()
  42. return
  43. }
  44. // STOP OMIT
  45. func main() {
  46. a()
  47. b()
  48. fmt.Println()
  49. fmt.Println(c())
  50. }