tour.golang.org 的练习

Stringers

/* Exercise: Stringers Make the IPAddr type implement fmt.Stringer to print the address as a dotted quad. For instance, IPAddr{1, 2, 3, 4} should print as "1.2.3.4". */ package main import ( "fmt" "strconv" "strings" ) type iPAddr [4]byte func (ip iPAddr) String() string { arr := []string{"0", ".", "0", ".", "0", ".", "0"} for i := 0; i < 4; i++ { arr[i<<1] = strconv.Itoa(int(ip[i])) } sip := strings.Join(arr, "") return sip } func main() { hosts := map[string]iPAddr{ "loopback": {127, 0, 0, 1}, "googleDNS": {8, 8, 8, 8}, } for name, ip := range hosts { fmt.

Web Crawler

/* Exercise: Web Crawler In this exercise you'll use Go's concurrency features to parallelize a web crawler. Modify the Crawl function to fetch URLs in parallel without fetching the same URL twice. Hint: you can keep a cache of the URLs that have been fetched on a map, but maps alone are not safe for concurrent use! */ package main import ( "fmt" ) type Fetcher interface { // Fetch returns the body of URL and // a slice of URLs found on that page.