A Tour of Go - 第2回 dwanGo
2回目.
package main import "fmt" // fibonacci is a function that returns // a function that returns an int. func fibonacci() func() int { x, y := 0, 1 return func() int { x, y = y, x+y return x } } func main() { f := fibonacci() for i := 0; i < 10; i++ { fmt.Println(f()) } }
package main import "fmt" import "math/cmplx" func Cbrt(x complex128) complex128 { z, z_prev := complex128(2), complex128(0) for ; cmplx.Abs(z-z_prev) > 1e-10; { z_prev = z z = z - (cmplx.Pow(z, 3) - x) / (3*(z*z)) } return z } func main() { fmt.Println(Cbrt(2)) fmt.Println(cmplx.Pow(Cbrt(2),3)) }
56
package main import ( "fmt" "math" ) type ErrNegativeSqrt float64 func (e ErrNegativeSqrt) Error() string { return fmt.Sprintf("cannot Sqrt negative number: %f", e) } func Sqrt(f float64) (float64, error) { if f < 0 { return 0, ErrNegativeSqrt(f) } z := 2. for i := 0; i < 10; i++ { z = z - (math.Pow(z, 2) - f) / (2 * z) } return z, nil } func main() { fmt.Println(Sqrt(2)) fmt.Println(Sqrt(-2)) }
58
package main import ( "net/http" ) type String string type Struct struct { Greeting string Punct string Who string } func (s String) ServeHTTP( w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, s) } func (s Struct) ServeHTTP( w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, s.Greeting, s.Punct, s.Who) } func main() { http.Handle("/string", String("I'm a frayed knot.")) http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"}) http.ListenAndServe("localhost:4000", nil) }
60
package main import ( "code.google.com/p/go-tour/pic" "image" "image/color" ) type Image struct{ Width int Height int } func (img *Image) ColorModel() color.Model { return color.RGBAModel } func (img *Image) Bounds() image.Rectangle { return image.Rect(0, 0, img.Width, img.Height) } func (img *Image) At(x, y int) color.Color { return color.RGBA{uint8(x*y), uint8(y-x), 255, 255} } func main() { m := &Image{100, 100} pic.ShowImage(m) }
61
package main import ( "io" "os" "strings" ) type rot13Reader struct { r io.Reader } func (rot *rot13Reader) Read (p []byte) (n int, err error) { n, err = rot.r.Read(p) for i := range p { if ('A' <= p[i] && p[i] <= 'M') || ('a' <= p[i] && p[i] <= 'm') { p[i] += 13 } else if ('N' <= p[i] && p[i] <= 'Z') || ('n' <= p[i] && p[i] <= 'z') { p[i] -= 13 } } return } func main() { s := strings.NewReader( "Lbh penpxrq gur pbqr!") r := rot13Reader{s} io.Copy(os.Stdout, &r) }