はじめに
こんにちは、Python界の情弱です。A Tour of Goを端からやってます。前回やってみた#43-47の演習問題に続いて、今度は#57-60をやってみます。
こんな感じ
#57 Errors
package main import ( "fmt" ) type ErrNegativeSqrt float64 func (e ErrNegativeSqrt) Error() string { return fmt.Sprintf("cannot Sqrt negative number: %f", e) } func Sqrt(x float64) (float64, error) { if x < 0 { return x, ErrNegativeSqrt(x) } z := 1.0 delta := z for delta > 0.001 { new_z := z - (z*z - x) / 2*z delta = new_z - z z = new_z } return z, nil } func main() { fmt.Println(Sqrt(2)) fmt.Println(Sqrt(-2)) }
#58 HTTP Handlers
package main import ( "fmt" "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.Fprintf(w, string(s)) } func (s Struct) ServeHTTP( w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "%s %s %s", s.Greeting, s.Punct, s.Who) } func main() { // your http.Handle calls here http.Handle("/string", String("I'm a frayed knot.")) http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"}) http.ListenAndServe("localhost:4000", nil) }
#59 Image
package main import ( "image" "image/color" "code.google.com/p/go-tour/pic" ) type Image struct{ width, height int } func (i Image) ColorModel() color.Model { return color.RGBAModel } func (i Image) Bounds() image.Rectangle { return image.Rect(0, 0, i.width, i.height) } func (i Image) At(x, y int) color.Color { v := uint8((x + y) % 255) return color.RGBA{v, v, 255, 255} } func main() { m := Image{100, 100} pic.ShowImage(m) }
#60 Rot13 Reader
package main import ( "io" "os" "strings" ) type rot13Reader struct { r io.Reader } func (rr *rot13Reader) Read(p []byte) (n int, err error) { n, err = rr.r.Read(p) for i := 0; i < len(p); i++ { if (p[i] >= 'A' && p[i] < 'N') || (p[i] >= 'a' && p[i] < 'n') { p[i] += 13 } else if (p[i] >= 'N' && p[i] <= 'Z') || (p[i] >= 'n' && p[i] <= 'z') { p[i] -= 13 } } return } func main() { s := strings.NewReader( "Lbh penpxrq gur pbqr!") r := rot13Reader{s} io.Copy(os.Stdout, &r) }