A Tour of Go Exercise: Errors】的更多相关文章

Copy your Sqrt function from the earlier exercises and modify it to return an error value. Sqrt should return a non-nil error value when given a negative number, as it doesn't support complex numbers. Create a new type type ErrNegativeSqrt float64 an…
Remember the picture generator you wrote earlier? Let's write another one, but this time it will return an implementation of image.Image instead of a slice of data. Define your own Image type, implement the necessary methods, and callpic.ShowImage. B…
Implement the following types and define ServeHTTP methods on them. Register them to handle specific paths in your web server. type String string type Struct struct { Greeting string Punct string Who string } For example, you should be able to regist…
Let's have some fun with functions. Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers. package main import "fmt" // fibonacci is a function that returns // a function that returns an int…
Implement WordCount. It should return a map of the counts of each “word” in the string s. The wc.Test function runs a test suite against the provided function and prints success or failure. You might find strings.Fields helpful. package main import (…
Implement Pic. It should return a slice of length dy, each element of which is a slice of dx 8-bit unsigned integers. When you run the program, it will display your picture, interpreting the integers as grayscale (well, bluescale) values. The choice…
As a simple way to play with functions and loops, implement the square root function using Newton's method. In this case, Newton's method is to approximate Sqrt(x) by picking a starting point z and then repeating: To begin with, just repeat that calc…
/* Exercise: Loops and Functions #43 */ package main import ( "fmt" "math" ) func Sqrt(x float64) float64 { z := float64(.) s := float64() for { z = z - (z*z - x)/(*z) { break } s = z } return s } func main() { fmt.Println(Sqrt()) fmt.…
Go for Pythonistas https://talks.golang.org/2013/go4python.slide#1 Things I don't like about Python (it'll be short) Beautiful and simple Dynamic typing - nice because it's concise, like Python. a = "hello" b = 1 # but also a = 2 Static typing -…
An error is anything that can describe itself as an error string. The idea is captured by the predefined, built-in interface type, error, with its single method, Error, returning a string: type error interface { Error() string } The fmt package's var…