go1.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 examples to embed in the Go 1 release notes document.
  5. package main
  6. import (
  7. "errors"
  8. "flag"
  9. "fmt"
  10. "log"
  11. "os"
  12. "path/filepath"
  13. "testing"
  14. "time"
  15. "unicode"
  16. )
  17. func main() {
  18. flag.Parse()
  19. stringAppend()
  20. mapDelete()
  21. mapIteration()
  22. multipleAssignment()
  23. structEquality()
  24. compositeLiterals()
  25. runeType()
  26. errorExample()
  27. timePackage()
  28. walkExample()
  29. osIsExist()
  30. }
  31. var timeout = flag.Duration("timeout", 30*time.Second, "how long to wait for completion")
  32. func init() {
  33. // canonicalize the logging
  34. log.SetFlags(0)
  35. }
  36. func mapDelete() {
  37. m := map[string]int{"7": 7, "23": 23}
  38. k := "7"
  39. delete(m, k)
  40. if m["7"] != 0 || m["23"] != 23 {
  41. log.Fatal("mapDelete:", m)
  42. }
  43. }
  44. func stringAppend() {
  45. greeting := []byte{}
  46. greeting = append(greeting, []byte("hello ")...)
  47. greeting = append(greeting, "world"...)
  48. if string(greeting) != "hello world" {
  49. log.Fatal("stringAppend: ", string(greeting))
  50. }
  51. }
  52. func mapIteration() {
  53. m := map[string]int{"Sunday": 0, "Monday": 1}
  54. for name, value := range m {
  55. // This loop should not assume Sunday will be visited first.
  56. f(name, value)
  57. }
  58. }
  59. func f(string, int) {
  60. }
  61. func assert(t bool) {
  62. if !t {
  63. log.Panic("assertion fail")
  64. }
  65. }
  66. func multipleAssignment() {
  67. sa := []int{1, 2, 3}
  68. i := 0
  69. i, sa[i] = 1, 2 // sets i = 1, sa[0] = 2
  70. sb := []int{1, 2, 3}
  71. j := 0
  72. sb[j], j = 2, 1 // sets sb[0] = 2, j = 1
  73. sc := []int{1, 2, 3}
  74. sc[0], sc[0] = 1, 2 // sets sc[0] = 1, then sc[0] = 2 (so sc[0] = 2 at end)
  75. assert(i == 1 && sa[0] == 2)
  76. assert(j == 1 && sb[0] == 2)
  77. assert(sc[0] == 2)
  78. }
  79. func structEquality() {
  80. type Day struct {
  81. long string
  82. short string
  83. }
  84. Christmas := Day{"Christmas", "XMas"}
  85. Thanksgiving := Day{"Thanksgiving", "Turkey"}
  86. holiday := map[Day]bool{
  87. Christmas: true,
  88. Thanksgiving: true,
  89. }
  90. fmt.Printf("Christmas is a holiday: %t\n", holiday[Christmas])
  91. }
  92. func compositeLiterals() {
  93. type Date struct {
  94. month string
  95. day int
  96. }
  97. // Struct values, fully qualified; always legal.
  98. holiday1 := []Date{
  99. Date{"Feb", 14},
  100. Date{"Nov", 11},
  101. Date{"Dec", 25},
  102. }
  103. // Struct values, type name elided; always legal.
  104. holiday2 := []Date{
  105. {"Feb", 14},
  106. {"Nov", 11},
  107. {"Dec", 25},
  108. }
  109. // Pointers, fully qualified, always legal.
  110. holiday3 := []*Date{
  111. &Date{"Feb", 14},
  112. &Date{"Nov", 11},
  113. &Date{"Dec", 25},
  114. }
  115. // Pointers, type name elided; legal in Go 1.
  116. holiday4 := []*Date{
  117. {"Feb", 14},
  118. {"Nov", 11},
  119. {"Dec", 25},
  120. }
  121. // STOP OMIT
  122. _, _, _, _ = holiday1, holiday2, holiday3, holiday4
  123. }
  124. func runeType() {
  125. // STARTRUNE OMIT
  126. delta := 'δ' // delta has type rune.
  127. var DELTA rune
  128. DELTA = unicode.ToUpper(delta)
  129. epsilon := unicode.ToLower(DELTA + 1)
  130. if epsilon != 'δ'+1 {
  131. log.Fatal("inconsistent casing for Greek")
  132. }
  133. // ENDRUNE OMIT
  134. }
  135. // START ERROR EXAMPLE OMIT
  136. type SyntaxError struct {
  137. File string
  138. Line int
  139. Message string
  140. }
  141. func (se *SyntaxError) Error() string {
  142. return fmt.Sprintf("%s:%d: %s", se.File, se.Line, se.Message)
  143. }
  144. // END ERROR EXAMPLE OMIT
  145. func errorExample() {
  146. var ErrSyntax = errors.New("syntax error")
  147. _ = ErrSyntax
  148. se := &SyntaxError{"file", 7, "error"}
  149. got := fmt.Sprint(se)
  150. const expect = "file:7: error"
  151. if got != expect {
  152. log.Fatalf("errorsPackage: expected %q got %q", expect, got)
  153. }
  154. }
  155. // sleepUntil sleeps until the specified time. It returns immediately if it's too late.
  156. func sleepUntil(wakeup time.Time) {
  157. now := time.Now() // A Time.
  158. if !wakeup.After(now) {
  159. return
  160. }
  161. delta := wakeup.Sub(now) // A Duration.
  162. fmt.Printf("Sleeping for %.3fs\n", delta.Seconds())
  163. time.Sleep(delta)
  164. }
  165. func timePackage() {
  166. sleepUntil(time.Now().Add(123 * time.Millisecond))
  167. }
  168. func walkExample() {
  169. // STARTWALK OMIT
  170. markFn := func(path string, info os.FileInfo, err error) error {
  171. if path == "pictures" { // Will skip walking of directory pictures and its contents.
  172. return filepath.SkipDir
  173. }
  174. if err != nil {
  175. return err
  176. }
  177. log.Println(path)
  178. return nil
  179. }
  180. err := filepath.Walk(".", markFn)
  181. if err != nil {
  182. log.Fatal(err)
  183. }
  184. // ENDWALK OMIT
  185. }
  186. func initializationFunction(c chan int) {
  187. c <- 1
  188. }
  189. var PackageGlobal int
  190. func init() {
  191. c := make(chan int)
  192. go initializationFunction(c)
  193. PackageGlobal = <-c
  194. }
  195. func BenchmarkSprintf(b *testing.B) {
  196. // Verify correctness before running benchmark.
  197. b.StopTimer()
  198. got := fmt.Sprintf("%x", 23)
  199. const expect = "17"
  200. if expect != got {
  201. b.Fatalf("expected %q; got %q", expect, got)
  202. }
  203. b.StartTimer()
  204. for i := 0; i < b.N; i++ {
  205. fmt.Sprintf("%x", 23)
  206. }
  207. }
  208. func osIsExist() {
  209. name := "go1.go"
  210. f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
  211. if os.IsExist(err) {
  212. log.Printf("%s already exists", name)
  213. }
  214. _ = f
  215. }