Created
September 27, 2012 17:40
-
-
Save fanzeyi/3795337 to your computer and use it in GitHub Desktop.
My answser for `A Tour of Go` Part II
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type ErrNegativeSqrt float64 | |
func (e ErrNegativeSqrt) Error() string { | |
return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e)) | |
} | |
func Sqrt(f float64) (float64, error) { | |
if f < 0 { | |
return 0.0,ErrNegativeSqrt(f) | |
} | |
z := f / 2 | |
for i := 0; i < 10; i++ { | |
z = z - (z * z - f) / (2 * z) | |
} | |
return z, nil | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
fmt.Println(Sqrt(-2.2)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "image" | |
import "image/color" | |
import "tour/pic" | |
type Image struct{} | |
func (img *Image) Bounds() image.Rectangle{ | |
return image.Rect(0, 0, 200, 200) | |
} | |
func (img *Image) ColorModel() color.Model { | |
return color.RGBAModel | |
} | |
func (img *Image) At(x,y int) color.Color { | |
return color.RGBA{2, 2, 255, 255} | |
} | |
func main() { | |
m := Image{} | |
pic.ShowImage(&m) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "io" | |
import "os" | |
import "strings" | |
type rot13Reader struct { | |
r io.Reader | |
} | |
func (r *rot13Reader) Read(b []byte) (int, error) { | |
cr,a := r.r.Read(b) | |
for i := range b { | |
if((b[i] >= 'A' && b[i] <= 'M') || (b[i] >= 'a' && b[i] <= 'm')) { | |
b[i] = b[i] + 13 | |
}else if((b[i] >= 'N' && b[i] <= 'Z') || (b[i] >= 'n' && b[i] <= 'z')) { | |
b[i] = b[i] - 13 | |
} | |
} | |
return cr,a | |
} | |
func main() { | |
s := strings.NewReader( | |
"Lbh penpxrq gur pbqr!") | |
r := rot13Reader{s} | |
io.Copy(os.Stdout, &r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment