diff options
Diffstat (limited to 'doc/progs')
-rw-r--r-- | doc/progs/cgo1.go | 21 | ||||
-rw-r--r-- | doc/progs/cgo2.go | 21 | ||||
-rw-r--r-- | doc/progs/cgo3.go | 17 | ||||
-rw-r--r-- | doc/progs/cgo4.go | 17 | ||||
-rw-r--r-- | doc/progs/gobs1.go | 22 | ||||
-rw-r--r-- | doc/progs/gobs2.go | 43 | ||||
-rw-r--r-- | doc/progs/helloworld.go | 11 | ||||
-rw-r--r-- | doc/progs/helloworld3.go | 21 | ||||
-rw-r--r-- | doc/progs/image_draw.go | 142 | ||||
-rw-r--r-- | doc/progs/interface.go | 6 | ||||
-rw-r--r-- | doc/progs/interface2.go | 20 | ||||
-rw-r--r-- | doc/progs/json1.go | 88 | ||||
-rw-r--r-- | doc/progs/json2.go | 42 | ||||
-rw-r--r-- | doc/progs/json3.go | 73 | ||||
-rw-r--r-- | doc/progs/json4.go | 45 | ||||
-rw-r--r-- | doc/progs/json5.go | 31 | ||||
-rw-r--r-- | doc/progs/print.go | 23 | ||||
-rw-r--r-- | doc/progs/print_string.go | 21 | ||||
-rwxr-xr-x | doc/progs/run | 46 | ||||
-rw-r--r-- | doc/progs/server.go | 51 | ||||
-rw-r--r-- | doc/progs/server1.go | 56 | ||||
-rw-r--r-- | doc/progs/sort.go | 59 | ||||
-rw-r--r-- | doc/progs/strings.go | 17 | ||||
-rw-r--r-- | doc/progs/sum.go | 21 | ||||
-rw-r--r-- | doc/progs/timeout1.go | 28 | ||||
-rw-r--r-- | doc/progs/timeout2.go | 27 |
26 files changed, 687 insertions, 282 deletions
diff --git a/doc/progs/cgo1.go b/doc/progs/cgo1.go new file mode 100644 index 000000000..b79ee368a --- /dev/null +++ b/doc/progs/cgo1.go @@ -0,0 +1,21 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package rand + +/* +#include <stdlib.h> +*/ +import "C" + +// STOP OMIT +func Random() int { + return int(C.random()) +} + +// STOP OMIT +func Seed(i int) { + C.srandom(C.uint(i)) +} + +// END OMIT diff --git a/doc/progs/cgo2.go b/doc/progs/cgo2.go new file mode 100644 index 000000000..f38473b13 --- /dev/null +++ b/doc/progs/cgo2.go @@ -0,0 +1,21 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package rand2 + +/* +#include <stdlib.h> +*/ +import "C" + +func Random() int { + var r C.long = C.random() + return int(r) +} + +// STOP OMIT +func Seed(i int) { + C.srandom(C.uint(i)) +} + +// END OMIT diff --git a/doc/progs/cgo3.go b/doc/progs/cgo3.go new file mode 100644 index 000000000..435fd0402 --- /dev/null +++ b/doc/progs/cgo3.go @@ -0,0 +1,17 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package print + +// #include <stdio.h> +// #include <stdlib.h> +import "C" +import "unsafe" + +func Print(s string) { + cs := C.CString(s) + C.fputs(cs, (*C.FILE)(C.stdout)) + C.free(unsafe.Pointer(cs)) +} + +// END OMIT diff --git a/doc/progs/cgo4.go b/doc/progs/cgo4.go new file mode 100644 index 000000000..3808d6217 --- /dev/null +++ b/doc/progs/cgo4.go @@ -0,0 +1,17 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package print + +// #include <stdio.h> +// #include <stdlib.h> +import "C" +import "unsafe" + +func Print(s string) { + cs := C.CString(s) + defer C.free(unsafe.Pointer(cs)) + C.fputs(cs, (*C.FILE)(C.stdout)) +} + +// END OMIT diff --git a/doc/progs/gobs1.go b/doc/progs/gobs1.go new file mode 100644 index 000000000..7077ca159 --- /dev/null +++ b/doc/progs/gobs1.go @@ -0,0 +1,22 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gobs1 + +type T struct{ X, Y, Z int } // Only exported fields are encoded and decoded. +var t = T{X: 7, Y: 0, Z: 8} + +// STOP OMIT + +type U struct{ X, Y *int8 } // Note: pointers to int8s +var u U + +// STOP OMIT + +type Node struct { + Value int + Left, Right *Node +} + +// STOP OMIT diff --git a/doc/progs/gobs2.go b/doc/progs/gobs2.go new file mode 100644 index 000000000..85bb41cdc --- /dev/null +++ b/doc/progs/gobs2.go @@ -0,0 +1,43 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "bytes" + "encoding/gob" + "fmt" + "log" +) + +type P struct { + X, Y, Z int + Name string +} + +type Q struct { + X, Y *int32 + Name string +} + +func main() { + // Initialize the encoder and decoder. Normally enc and dec would be + // bound to network connections and the encoder and decoder would + // run in different processes. + var network bytes.Buffer // Stand-in for a network connection + enc := gob.NewEncoder(&network) // Will write to network. + dec := gob.NewDecoder(&network) // Will read from network. + // Encode (send) the value. + err := enc.Encode(P{3, 4, 5, "Pythagoras"}) + if err != nil { + log.Fatal("encode error:", err) + } + // Decode (receive) the value. + var q Q + err = dec.Decode(&q) + if err != nil { + log.Fatal("decode error:", err) + } + fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y) +} diff --git a/doc/progs/helloworld.go b/doc/progs/helloworld.go deleted file mode 100644 index 8185038d9..000000000 --- a/doc/progs/helloworld.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import fmt "fmt" // Package implementing formatted I/O. - -func main() { - fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n") -} diff --git a/doc/progs/helloworld3.go b/doc/progs/helloworld3.go deleted file mode 100644 index 05d26df1c..000000000 --- a/doc/progs/helloworld3.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "./file" - "fmt" - "os" -) - -func main() { - hello := []byte("hello, world\n") - file.Stdout.Write(hello) - f, err := file.Open("/does/not/exist") - if f == nil { - fmt.Printf("can't open file; err=%s\n", err.Error()) - os.Exit(1) - } -} diff --git a/doc/progs/image_draw.go b/doc/progs/image_draw.go new file mode 100644 index 000000000..f3400b601 --- /dev/null +++ b/doc/progs/image_draw.go @@ -0,0 +1,142 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code snippets included in "The Go image/draw package." + +package main + +import ( + "image" + "image/color" + "image/draw" +) + +func main() { + Color() + Rect() + RectAndScroll() + ConvAndCircle() + Glyph() +} + +func Color() { + c := color.RGBA{255, 0, 255, 255} + r := image.Rect(0, 0, 640, 480) + dst := image.NewRGBA(r) + + // ZERO OMIT + // image.ZP is the zero point -- the origin. + draw.Draw(dst, r, &image.Uniform{c}, image.ZP, draw.Src) + // STOP OMIT + + // BLUE OMIT + m := image.NewRGBA(image.Rect(0, 0, 640, 480)) + blue := color.RGBA{0, 0, 255, 255} + draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src) + // STOP OMIT + + // RESET OMIT + draw.Draw(m, m.Bounds(), image.Transparent, image.ZP, draw.Src) + // STOP OMIT +} + +func Rect() { + dst := image.NewRGBA(image.Rect(0, 0, 640, 480)) + sr := image.Rect(0, 0, 200, 200) + src := image.Black + dp := image.Point{100, 100} + + // RECT OMIT + r := image.Rectangle{dp, dp.Add(sr.Size())} + draw.Draw(dst, r, src, sr.Min, draw.Src) + // STOP OMIT +} + +func RectAndScroll() { + dst := image.NewRGBA(image.Rect(0, 0, 640, 480)) + sr := image.Rect(0, 0, 200, 200) + src := image.Black + dp := image.Point{100, 100} + + // RECT2 OMIT + r := sr.Sub(sr.Min).Add(dp) + draw.Draw(dst, r, src, sr.Min, draw.Src) + // STOP OMIT + + m := dst + + // SCROLL OMIT + b := m.Bounds() + p := image.Pt(0, 20) + // Note that even though the second argument is b, + // the effective rectangle is smaller due to clipping. + draw.Draw(m, b, m, b.Min.Add(p), draw.Src) + dirtyRect := b.Intersect(image.Rect(b.Min.X, b.Max.Y-20, b.Max.X, b.Max.Y)) + // STOP OMIT + + _ = dirtyRect // noop +} + +func ConvAndCircle() { + src := image.NewRGBA(image.Rect(0, 0, 640, 480)) + dst := image.NewRGBA(image.Rect(0, 0, 640, 480)) + + // CONV OMIT + b := src.Bounds() + m := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy())) + draw.Draw(m, m.Bounds(), src, b.Min, draw.Src) + // STOP OMIT + + p := image.Point{100, 100} + r := 50 + + // CIRCLE2 OMIT + draw.DrawMask(dst, dst.Bounds(), src, image.ZP, &circle{p, r}, image.ZP, draw.Over) + // STOP OMIT +} + +func theGlyphImageForAFont() image.Image { + return image.NewRGBA(image.Rect(0, 0, 640, 480)) +} + +func theBoundsFor(index int) image.Rectangle { + return image.Rect(0, 0, 32, 32) +} + +func Glyph() { + p := image.Point{100, 100} + dst := image.NewRGBA(image.Rect(0, 0, 640, 480)) + glyphIndex := 42 + + // GLYPH OMIT + src := &image.Uniform{color.RGBA{0, 0, 255, 255}} + mask := theGlyphImageForAFont() + mr := theBoundsFor(glyphIndex) + draw.DrawMask(dst, mr.Sub(mr.Min).Add(p), src, image.ZP, mask, mr.Min, draw.Over) + // STOP OMIT +} + +//CIRCLE OMIT +type circle struct { + p image.Point + r int +} + +func (c *circle) ColorModel() color.Model { + return color.AlphaModel +} + +func (c *circle) Bounds() image.Rectangle { + return image.Rect(c.p.X-c.r, c.p.Y-c.r, c.p.X+c.r, c.p.Y+c.r) +} + +func (c *circle) At(x, y int) color.Color { + xx, yy, rr := float64(x-c.p.X)+0.5, float64(y-c.p.Y)+0.5, float64(c.r) + if xx*xx+yy*yy < rr*rr { + return color.Alpha{255} + } + return color.Alpha{0} +} + +//STOP diff --git a/doc/progs/interface.go b/doc/progs/interface.go index 91145401e..c2925d590 100644 --- a/doc/progs/interface.go +++ b/doc/progs/interface.go @@ -1,3 +1,9 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code snippets included in "The Laws of Reflection." + package main import ( diff --git a/doc/progs/interface2.go b/doc/progs/interface2.go index e2716cf16..a541d94e4 100644 --- a/doc/progs/interface2.go +++ b/doc/progs/interface2.go @@ -1,3 +1,9 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code snippets included in "The Laws of Reflection." + package main import ( @@ -39,11 +45,14 @@ func f3() { type MyInt int var x MyInt = 7 v := reflect.ValueOf(x) + // STOP OMIT // START f3b OMIT y := v.Interface().(float64) // y will have type float64. fmt.Println(y) + // STOP OMIT // START f3c OMIT fmt.Println(v.Interface()) + // STOP OMIT // START f3d OMIT fmt.Printf("value is %7.1e\n", v.Interface()) // STOP OMIT @@ -69,6 +78,7 @@ func f6() { // START f6 OMIT var x float64 = 3.4 v := reflect.ValueOf(x) + // STOP OMIT // START f6b OMIT v.SetFloat(7.1) // STOP OMIT @@ -80,9 +90,11 @@ func f7() { p := reflect.ValueOf(&x) // Note: take the address of x. fmt.Println("type of p:", p.Type()) fmt.Println("settability of p:", p.CanSet()) + // STOP OMIT // START f7b OMIT v := p.Elem() fmt.Println("settability of v:", v.CanSet()) + // STOP OMIT // START f7c OMIT v.SetFloat(7.1) fmt.Println(v.Interface()) @@ -104,9 +116,17 @@ func f8() { fmt.Printf("%d: %s %s = %v\n", i, typeOfT.Field(i).Name, f.Type(), f.Interface()) } + // STOP OMIT // START f8b OMIT s.Field(0).SetInt(77) s.Field(1).SetString("Sunset Strip") fmt.Println("t is now", t) // STOP OMIT } + +func f9() { + // START f9 OMIT + var x float64 = 3.4 + fmt.Println("value:", reflect.ValueOf(x)) + // STOP OMIT +} diff --git a/doc/progs/json1.go b/doc/progs/json1.go new file mode 100644 index 000000000..9e10f4743 --- /dev/null +++ b/doc/progs/json1.go @@ -0,0 +1,88 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "encoding/json" + "log" + "reflect" +) + +type Message struct { + Name string + Body string + Time int64 +} + +// STOP OMIT + +func Encode() { + m := Message{"Alice", "Hello", 1294706395881547000} + b, err := json.Marshal(m) + + if err != nil { + panic(err) + } + + expected := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`) + if !reflect.DeepEqual(b, expected) { + log.Panicf("Error marshalling %q, expected %q, got %q.", m, expected, b) + } + +} + +func Decode() { + b := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`) + var m Message + err := json.Unmarshal(b, &m) + + if err != nil { + panic(err) + } + + expected := Message{ + Name: "Alice", + Body: "Hello", + Time: 1294706395881547000, + } + + if !reflect.DeepEqual(m, expected) { + log.Panicf("Error unmarshalling %q, expected %q, got %q.", b, expected, m) + } + + m = Message{ + Name: "Alice", + Body: "Hello", + Time: 1294706395881547000, + } + + // STOP OMIT +} + +func PartialDecode() { + b := []byte(`{"Name":"Bob","Food":"Pickle"}`) + var m Message + err := json.Unmarshal(b, &m) + + // STOP OMIT + + if err != nil { + panic(err) + } + + expected := Message{ + Name: "Bob", + } + + if !reflect.DeepEqual(expected, m) { + log.Panicf("Error unmarshalling %q, expected %q, got %q.", b, expected, m) + } +} + +func main() { + Encode() + Decode() + PartialDecode() +} diff --git a/doc/progs/json2.go b/doc/progs/json2.go new file mode 100644 index 000000000..6089ae671 --- /dev/null +++ b/doc/progs/json2.go @@ -0,0 +1,42 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "fmt" + "math" +) + +func InterfaceExample() { + var i interface{} + i = "a string" + i = 2011 + i = 2.777 + + // STOP OMIT + + r := i.(float64) + fmt.Println("the circle's area", math.Pi*r*r) + + // STOP OMIT + + switch v := i.(type) { + case int: + fmt.Println("twice i is", v*2) + case float64: + fmt.Println("the reciprocal of i is", 1/v) + case string: + h := len(v) / 2 + fmt.Println("i swapped by halves is", v[h:]+v[:h]) + default: + // i isn't one of the types above + } + + // STOP OMIT +} + +func main() { + InterfaceExample() +} diff --git a/doc/progs/json3.go b/doc/progs/json3.go new file mode 100644 index 000000000..a04fdfa50 --- /dev/null +++ b/doc/progs/json3.go @@ -0,0 +1,73 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "encoding/json" + "fmt" + "log" + "reflect" +) + +func Decode() { + b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`) + + var f interface{} + err := json.Unmarshal(b, &f) + + // STOP OMIT + + if err != nil { + panic(err) + } + + expected := map[string]interface{}{ + "Name": "Wednesday", + "Age": float64(6), + "Parents": []interface{}{ + "Gomez", + "Morticia", + }, + } + + if !reflect.DeepEqual(f, expected) { + log.Panicf("Error unmarshalling %q, expected %q, got %q", b, expected, f) + } + + f = map[string]interface{}{ + "Name": "Wednesday", + "Age": 6, + "Parents": []interface{}{ + "Gomez", + "Morticia", + }, + } + + // STOP OMIT + + m := f.(map[string]interface{}) + + for k, v := range m { + switch vv := v.(type) { + case string: + fmt.Println(k, "is string", vv) + case int: + fmt.Println(k, "is int", vv) + case []interface{}: + fmt.Println(k, "is an array:") + for i, u := range vv { + fmt.Println(i, u) + } + default: + fmt.Println(k, "is of a type I don't know how to handle") + } + } + + // STOP OMIT +} + +func main() { + Decode() +} diff --git a/doc/progs/json4.go b/doc/progs/json4.go new file mode 100644 index 000000000..492630220 --- /dev/null +++ b/doc/progs/json4.go @@ -0,0 +1,45 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "encoding/json" + "log" + "reflect" +) + +type FamilyMember struct { + Name string + Age int + Parents []string +} + +// STOP OMIT + +func Decode() { + b := []byte(`{"Name":"Bob","Age":20,"Parents":["Morticia", "Gomez"]}`) + var m FamilyMember + err := json.Unmarshal(b, &m) + + // STOP OMIT + + if err != nil { + panic(err) + } + + expected := FamilyMember{ + Name: "Bob", + Age: 20, + Parents: []string{"Morticia", "Gomez"}, + } + + if !reflect.DeepEqual(expected, m) { + log.Panicf("Error unmarshalling %q, expected %q, got %q", b, expected, m) + } +} + +func main() { + Decode() +} diff --git a/doc/progs/json5.go b/doc/progs/json5.go new file mode 100644 index 000000000..6d7a4ca8c --- /dev/null +++ b/doc/progs/json5.go @@ -0,0 +1,31 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "encoding/json" + "log" + "os" +) + +func main() { + dec := json.NewDecoder(os.Stdin) + enc := json.NewEncoder(os.Stdout) + for { + var v map[string]interface{} + if err := dec.Decode(&v); err != nil { + log.Println(err) + return + } + for k := range v { + if k != "Name" { + delete(v, k) + } + } + if err := enc.Encode(&v); err != nil { + log.Println(err) + } + } +} diff --git a/doc/progs/print.go b/doc/progs/print.go deleted file mode 100644 index 8f44ba8c6..000000000 --- a/doc/progs/print.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -func main() { - var u64 uint64 = 1<<64 - 1 - fmt.Printf("%d %d\n", u64, int64(u64)) - - // harder stuff - type T struct { - a int - b string - } - t := T{77, "Sunset Strip"} - a := []int{1, 2, 3, 4} - fmt.Printf("%v %v %v\n", u64, t, a) - fmt.Print(u64, " ", t, " ", a, "\n") - fmt.Println(u64, t, a) -} diff --git a/doc/progs/print_string.go b/doc/progs/print_string.go deleted file mode 100644 index 46ab1d91a..000000000 --- a/doc/progs/print_string.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -type testType struct { - a int - b string -} - -func (t *testType) String() string { - return fmt.Sprint(t.a) + " " + t.b -} - -func main() { - t := &testType{77, "Sunset Strip"} - fmt.Println(t) -} diff --git a/doc/progs/run b/doc/progs/run index e3d5c128c..8348a33e5 100755 --- a/doc/progs/run +++ b/doc/progs/run @@ -5,6 +5,8 @@ set -e +goos=$(go env GOOS) + defer_panic_recover=" defer defer2 @@ -23,14 +25,48 @@ error_handling=" error4 " -all=$(echo $defer_panic_recover $effective_go $error_handling slices go1) +law_of_reflection=" + interface + interface2 +" + +c_go_cgo=" + cgo1 + cgo2 + cgo3 + cgo4 +" +# cgo1 and cgo2 don't run on freebsd, srandom has a different signature +if [ "$goos" == "freebsd" ]; then + c_go_cgo="cgo3 cgo4" +fi + +timeout=" + timeout1 + timeout2 +" + +gobs=" + gobs1 + gobs2 +" + +json=" + json1 + json2 + json3 + json4 + json5 +" + +all=$(echo $defer_panic_recover $effective_go $error_handling $law_of_reflection $c_go_cgo $timeout $gobs $json slices go1) for i in $all; do go build $i.go done # Write to temporary file to avoid mingw bash bug. -TMPFILE="/tmp/gotest3.$USER" +TMPFILE="${TMPDIR:-/tmp}/gotest3.$USER" function testit { ./$1 >"$TMPFILE" 2>&1 || true @@ -50,4 +86,10 @@ testit eff_sequence '^\[-1 2 6 16 44\]$' testit go1 '^Christmas is a holiday: true Sleeping for 0.123s.*go1.go already exists$' +testit interface2 "^type: float64$" +testit json1 "^$" +testit json2 "the reciprocal of i is" +testit json3 "Age is int 6" +testit json4 "^$" + rm -f $all "$TMPFILE" diff --git a/doc/progs/server.go b/doc/progs/server.go deleted file mode 100644 index 4d8409b80..000000000 --- a/doc/progs/server.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -type request struct { - a, b int - replyc chan int -} - -type binOp func(a, b int) int - -func run(op binOp, req *request) { - reply := op(req.a, req.b) - req.replyc <- reply -} - -func server(op binOp, service <-chan *request) { - for { - req := <-service - go run(op, req) // don't wait for it - } -} - -func startServer(op binOp) chan<- *request { - req := make(chan *request) - go server(op, req) - return req -} - -func main() { - adder := startServer(func(a, b int) int { return a + b }) - const N = 100 - var reqs [N]request - for i := 0; i < N; i++ { - req := &reqs[i] - req.a = i - req.b = i + N - req.replyc = make(chan int) - adder <- req - } - for i := N - 1; i >= 0; i-- { // doesn't matter what order - if <-reqs[i].replyc != N+2*i { - fmt.Println("fail at", i) - } - } - fmt.Println("done") -} diff --git a/doc/progs/server1.go b/doc/progs/server1.go deleted file mode 100644 index 39e3dde5d..000000000 --- a/doc/progs/server1.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -type request struct { - a, b int - replyc chan int -} - -type binOp func(a, b int) int - -func run(op binOp, req *request) { - reply := op(req.a, req.b) - req.replyc <- reply -} - -func server(op binOp, service <-chan *request, quit <-chan bool) { - for { - select { - case req := <-service: - go run(op, req) // don't wait for it - case <-quit: - return - } - } -} - -func startServer(op binOp) (service chan *request, quit chan bool) { - service = make(chan *request) - quit = make(chan bool) - go server(op, service, quit) - return service, quit -} - -func main() { - adder, quit := startServer(func(a, b int) int { return a + b }) - const N = 100 - var reqs [N]request - for i := 0; i < N; i++ { - req := &reqs[i] - req.a = i - req.b = i + N - req.replyc = make(chan int) - adder <- req - } - for i := N - 1; i >= 0; i-- { // doesn't matter what order - if <-reqs[i].replyc != N+2*i { - fmt.Println("fail at", i) - } - } - quit <- true -} diff --git a/doc/progs/sort.go b/doc/progs/sort.go deleted file mode 100644 index 894693f0d..000000000 --- a/doc/progs/sort.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package sort - -type Interface interface { - Len() int - Less(i, j int) bool - Swap(i, j int) -} - -func Sort(data Interface) { - for i := 1; i < data.Len(); i++ { - for j := i; j > 0 && data.Less(j, j-1); j-- { - data.Swap(j, j-1) - } - } -} - -func IsSorted(data Interface) bool { - n := data.Len() - for i := n - 1; i > 0; i-- { - if data.Less(i, i-1) { - return false - } - } - return true -} - -// Convenience types for common cases - -type IntSlice []int - -func (p IntSlice) Len() int { return len(p) } -func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] } -func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -type Float64Slice []float64 - -func (p Float64Slice) Len() int { return len(p) } -func (p Float64Slice) Less(i, j int) bool { return p[i] < p[j] } -func (p Float64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -type StringSlice []string - -func (p StringSlice) Len() int { return len(p) } -func (p StringSlice) Less(i, j int) bool { return p[i] < p[j] } -func (p StringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// Convenience wrappers for common cases - -func SortInts(a []int) { Sort(IntSlice(a)) } -func SortFloat64s(a []float64) { Sort(Float64Slice(a)) } -func SortStrings(a []string) { Sort(StringSlice(a)) } - -func IntsAreSorted(a []int) bool { return IsSorted(IntSlice(a)) } -func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Slice(a)) } -func StringsAreSorted(a []string) bool { return IsSorted(StringSlice(a)) } diff --git a/doc/progs/strings.go b/doc/progs/strings.go deleted file mode 100644 index e6739b385..000000000 --- a/doc/progs/strings.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "os" - -func main() { - s := "hello" - if s[1] != 'e' { - os.Exit(1) - } - s = "good bye" - var p *string = &s - *p = "ciao" -} diff --git a/doc/progs/sum.go b/doc/progs/sum.go deleted file mode 100644 index 0f316bc01..000000000 --- a/doc/progs/sum.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -func sum(a []int) int { // returns an int - s := 0 - for i := 0; i < len(a); i++ { - s += a[i] - } - return s -} - -func main() { - x := [3]int{1, 2, 3} - s := sum(x[:]) // a slice of the array is passed to sum - fmt.Print(s, "\n") -} diff --git a/doc/progs/timeout1.go b/doc/progs/timeout1.go new file mode 100644 index 000000000..5221770ec --- /dev/null +++ b/doc/progs/timeout1.go @@ -0,0 +1,28 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package timeout + +import ( + "time" +) + +func Timeout() { + ch := make(chan bool, 1) + timeout := make(chan bool, 1) + go func() { + time.Sleep(1 * time.Second) + timeout <- true + }() + + // STOP OMIT + + select { + case <-ch: + // a read from ch has occurred + case <-timeout: + // the read from ch has timed out + } + + // STOP OMIT +} diff --git a/doc/progs/timeout2.go b/doc/progs/timeout2.go new file mode 100644 index 000000000..7145bc93e --- /dev/null +++ b/doc/progs/timeout2.go @@ -0,0 +1,27 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +package query + +type Conn string + +func (c Conn) DoQuery(query string) Result { + return Result("result") +} + +type Result string + +func Query(conns []Conn, query string) Result { + ch := make(chan Result, 1) + for _, conn := range conns { + go func(c Conn) { + select { + case ch <- c.DoQuery(query): + default: + } + }(conn) + } + return <-ch +} + +// STOP OMIT |