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