Last active
August 15, 2022 07:48
-
-
Save hanks/cfc1ccb1940d41417abc to your computer and use it in GitHub Desktop.
Exercises for a tour of go
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
// Exercise: Loops and Functions | |
package main | |
import ( | |
"fmt" | |
) | |
func Sqrt(x float64) float64 { | |
z := 1.0 | |
for i := 0; i < 10; i++ { | |
z = z - ((z * z) - x) / (2 * z); | |
} | |
return z | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
} | |
// Exercise: Slices | |
package main | |
import "golang.org/x/tour/pic" | |
func Pic(dx, dy int) [][]uint8 { | |
result := make([][]uint8, dy) | |
for i := range result { | |
result[i] = make([]uint8, dx) | |
} | |
for i := 0; i < dy; i++ { | |
for j := 0; j < dx; j++ { | |
result[i][j] = uint8(i * j) | |
} | |
} | |
return result | |
} | |
func main() { | |
pic.Show(Pic) | |
} | |
// Exercise: Maps | |
package main | |
import ( | |
"golang.org/x/tour/wc" | |
"strings" | |
) | |
func WordCount(s string) map[string]int { | |
words := strings.Fields(s) | |
maps := make(map[string]int) | |
for _, word := range words { | |
maps[word] = maps[word] + 1 | |
} | |
return maps | |
} | |
func main() { | |
wc.Test(WordCount) | |
} | |
// Exercise: Fibonacci closure | |
package main | |
import "fmt" | |
// fibonacci is a function that returns | |
// a function that returns an int. | |
func fibonacci() func() int { | |
a := 1 | |
b := 1 | |
return func() int { | |
b = a + b | |
a = b - a | |
return a | |
} | |
} | |
func main() { | |
f := fibonacci() | |
for i := 0; i < 10; i++ { | |
fmt.Println(f()) | |
} | |
} | |
// Exercise: Stringers | |
package main | |
import "fmt" | |
type IPAddr [4]byte | |
// TODO: Add a "String() string" method to IPAddr. | |
func (ip IPAddr)String() string { | |
return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[3]) | |
} | |
func main() { | |
addrs := map[string]IPAddr{ | |
"loopback": {127, 0, 0, 1}, | |
"googleDNS": {8, 8, 8, 8}, | |
} | |
for n, a := range addrs { | |
fmt.Printf("%v: %v\n", n, a) | |
} | |
} | |
// Exercise: Errors | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
type ErrNegativeSqrt float64 | |
func (e ErrNegativeSqrt) Error() string { | |
return fmt.Sprintf("cannot Sqrt negative %v", float64(e)) | |
} | |
func Sqrt(x float64) (float64, error) { | |
if x < 0 { | |
return 0, ErrNegativeSqrt(x) | |
} | |
return math.Sqrt(x), nil | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
fmt.Println(Sqrt(-2)) | |
} | |
// Exercise: Readers | |
package main | |
import "golang.org/x/tour/reader" | |
type MyReader struct{} | |
// TODO: Add a Read([]byte) (int, error) method to MyReader. | |
func (r MyReader) Read(b []byte) (int, error) { | |
b[0] = 'A' | |
return 1, nil | |
} | |
func main() { | |
reader.Validate(MyReader{}) | |
} | |
// Exercise: rot13Reader | |
package main | |
import ( | |
"io" | |
"os" | |
"strings" | |
) | |
type rot13Reader struct { | |
r io.Reader | |
} | |
const FROM = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz " | |
const TO = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm " | |
func getMap(from string, to string) map[byte] byte { | |
aMap := make(map[byte] byte) | |
for i := 0; i < len(from); i++ { | |
aMap[from[i]] = to[i]; | |
} | |
return aMap | |
} | |
func rot13(b byte) byte { | |
aMap := getMap(FROM, TO) | |
return aMap[b] | |
} | |
func (r rot13Reader) Read(b []byte) (int, error) { | |
n, err := r.r.Read(b) | |
if err != nil { | |
return -1, err | |
} | |
for i := 0; i < n; i++ { | |
b[i] = rot13(b[i]); | |
} | |
return n, nil | |
} | |
func main() { | |
s := strings.NewReader("Lbh penpxrq gur pbqr!") | |
r := rot13Reader{s} | |
io.Copy(os.Stdout, &r) | |
} | |
// Exercise: HTTP Handlers | |
package main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
) | |
type String string | |
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprint(w, s) | |
} | |
type Struct struct { | |
Greeting string | |
Punct string | |
Who string | |
} | |
func (s *Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprint(w, 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!"}) | |
log.Fatal(http.ListenAndServe("localhost:4000", nil)) | |
} | |
// Exercise: Images | |
package main | |
import ( | |
"golang.org/x/tour/pic" | |
"image" | |
"image/color" | |
) | |
type Image struct{} | |
func (img Image) Bounds() image.Rectangle { | |
return image.Rectangle{ | |
image.Point{0, 0}, | |
image.Point{300, 300}, | |
} | |
} | |
func (img Image) ColorModel() color.Model { | |
return color.RGBAModel | |
} | |
func (img Image) At(x, y int) color.Color { | |
return color.RGBA{uint8(x % 256), uint8(y % 256), uint8((x * y) % 256 ), 255} | |
} | |
func main() { | |
m := Image{} | |
pic.ShowImage(m) | |
} | |
// Exercise: Equivalent Binary Trees | |
package main | |
import ( | |
"golang.org/x/tour/tree" | |
"fmt" | |
) | |
func WalkHelper(t *tree.Tree, ch chan int) { | |
if t != nil { | |
WalkHelper(t.Left, ch) | |
ch <- t.Value | |
WalkHelper(t.Right, ch) | |
} | |
} | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int) { | |
WalkHelper(t, ch) | |
close(ch) | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
ch1 := make(chan int) | |
ch2 := make(chan int) | |
go Walk(t1, ch1) | |
go Walk(t2, ch2) | |
for n1 := range ch1 { | |
n2, ok := <- ch2 | |
if n1 != n2 || !ok { | |
return false | |
} | |
} | |
return true | |
} | |
func main() { | |
ch := make(chan int) | |
go Walk(tree.New(1), ch) | |
for i := range ch { | |
fmt.Println(i) | |
} | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(Same(tree.New(1), tree.New(2))) | |
} | |
// Exercise: Web Crawler | |
package main | |
import ( | |
"fmt" | |
) | |
type Fetcher interface { | |
// Fetch returns the body of URL and | |
// a slice of URLs found on that page. | |
Fetch(url string) (body string, urls []string, err error) | |
} | |
var vis = make(map[string]bool) | |
// Crawl uses fetcher to recursively crawl | |
// pages starting with url, to a maximum of depth. | |
func Crawl(url string, depth int, fetcher Fetcher, ret chan string) { | |
defer close(ret) | |
if depth <= 0 { | |
return | |
} | |
if vis[url] { | |
return | |
} | |
vis[url] = true | |
body, urls, err := fetcher.Fetch(url) | |
if err != nil { | |
ret <- err.Error() | |
return | |
} | |
ret <- fmt.Sprintf("found: %s %q", url, body) | |
result := make([]chan string, len(urls)) | |
for i, u := range urls { | |
result[i] = make(chan string) | |
go Crawl(u, depth-1, fetcher, result[i]) | |
} | |
for i := range result { | |
for s := range result[i] { | |
ret <- s | |
} | |
} | |
return | |
} | |
func main() { | |
result := make(chan string) | |
go Crawl("http://golang.org/", 4, fetcher, result) | |
for s := range result { | |
fmt.Println(s) | |
} | |
} | |
// fakeFetcher is Fetcher that returns canned results. | |
type fakeFetcher map[string]*fakeResult | |
type fakeResult struct { | |
body string | |
urls []string | |
} | |
func (f fakeFetcher) Fetch(url string) (string, []string, error) { | |
if res, ok := f[url]; ok { | |
return res.body, res.urls, nil | |
} | |
return "", nil, fmt.Errorf("not found: %s", url) | |
} | |
// fetcher is a populated fakeFetcher. | |
var fetcher = fakeFetcher{ | |
"http://golang.org/": &fakeResult{ | |
"The Go Programming Language", | |
[]string{ | |
"http://golang.org/pkg/", | |
"http://golang.org/cmd/", | |
}, | |
}, | |
"http://golang.org/pkg/": &fakeResult{ | |
"Packages", | |
[]string{ | |
"http://golang.org/", | |
"http://golang.org/cmd/", | |
"http://golang.org/pkg/fmt/", | |
"http://golang.org/pkg/os/", | |
}, | |
}, | |
"http://golang.org/pkg/fmt/": &fakeResult{ | |
"Package fmt", | |
[]string{ | |
"http://golang.org/", | |
"http://golang.org/pkg/", | |
}, | |
}, | |
"http://golang.org/pkg/os/": &fakeResult{ | |
"Package os", | |
[]string{ | |
"http://golang.org/", | |
"http://golang.org/pkg/", | |
}, | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment