go-tour练习解答

简介:

go-tour对于想学习golang的人来说是一个很好的教程。

首先go-tour是有web版本,但是需要FQ。如果不能FQ的,也可以在google code上自己下载go-tour源码,go build,run一下,在自己的机器上就可以跑这个教程了。

提醒下,如果是后者,这篇文章中的程序对应的import包就需要进行相应修改了。

下面给出我的go-tour中的Exercise的解答(在web上已经测试通过)

Exercise: Loops and Functions

第一个循环10次:

复制代码
package main
import (
     "fmt"
)

func Sqrt(x float64) float64 {
     z := float64(1)
     for i := 0; i <= 10; i++ {
          z = z - (z*z - x) / (2 * z)
     }
     return z
}

func main() {
     fmt.Println(Sqrt(2))
}
复制代码

第二次无限接近:

复制代码
package main

import (
     "fmt"
     "math"
)

func Sqrt(x float64) float64 {
     z := float64(1)

     for {
          y := z - (z*z - x) / (2 * z)
          if math.Abs(y - z) < 1e-10 {
               return y
          }
          z = y;
     }
     return z
}



func main() {
     fmt.Println(Sqrt(2))
     fmt.Println(math.Sqrt(2))
}
复制代码

Exercise: Maps

复制代码
package main

import (
     "tour/wc"
     "strings"
)

func WordCount(s string) map[string]int {
     ret := make(map[string]int)

     arr := strings.Fields(s)
     for _, val := range arr {
          ret[val]++
     }
     return ret
}

func main() {
     wc.Test(WordCount)
}
复制代码

Exercise: Slices

复制代码
package main

import "tour/pic"

func Pic(dx, dy int) [][]uint8 {
     ret := make([][]uint8, dy)
     for i:=0; i<dy; i++ {
          ret[i] = make([]uint8, dx)
          for j:=0; j<dx; j++ {
               ret[i][j] = uint8(i*j)
          }
     }
     return ret
}

func main() {
     pic.Show(Pic)
}
复制代码

Exercise: Fibonacci closure

复制代码
package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
     sum1 := 0
     sum2 := 1
     return func() int{
          out := sum1 + sum2
          sum1 = sum2
          sum2 = out
          return out
         
     }
}

func main() {
     f := fibonacci()
     for i := 0; i < 10; i++ {
          fmt.Println(f())
     }
}
复制代码

Advanced Exercise: Complex cube roots

复制代码
package main

import (
     "fmt"
     "math/cmplx"
     )

func Cbrt(x complex128) complex128 {
     z := complex128(1)
     for {
          if y := z-(cmplx.Pow(z,3) - x)/(3 * z * z); cmplx.Abs(y - z) < 1e-10 {
               return y
          } else {
               z = y
          }
     }
     return z
}

func main() {
     fmt.Println(Cbrt(2))
}
复制代码

Exercise: Errors

复制代码
package main

import (
     "fmt"
     "math"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
     return "cannot Sqrt negative number:" + fmt.Sprint(float64(e))
}

func Sqrt(f float64) (float64, error) {
     if f < 0 {
          return 0, ErrNegativeSqrt(f)
     }
    
     z := float64(1)
     for {
          y := z - (z*z-f)/(2*z)
          if math.Abs(y-z) < 1e-10 {
               return y, nil
          }
          z = y
     }
     return z, nil
}

func main() {
     fmt.Println(Sqrt(2))
     fmt.Println(Sqrt(-2))
}
复制代码

Exercise: Images

复制代码
package main

import (
     "image"
     "tour/pic"
     "image/color"
)

type Image struct{
     W int
     H int
}

func(self Image) Bounds() image.Rectangle {
     return image.Rect(0, 0, self.W, self.H)
}

func(self Image) ColorModel() color.Model {
     return color.RGBAModel
}

func(self Image) At(x,y int) color.Color {
     return color.RGBA{uint8(x), uint8(y), 255, 255}
}

func main() {
     m := Image{W:100, H:100}
     pic.ShowImage(m)
}
复制代码

Exercise: Rot13 Reader

复制代码
package main

import (
     "io"
     "os"
     "strings"
)

type rot13Reader struct {
     r io.Reader
}

func(self rot13Reader)Read(p []byte) (n int, err error){
     self.r.Read(p)
     leng := len(p)
     for i := 0; i < leng; i++ {
          switch{
          case p[i] >= 'a' && p[i] < 'n':
               fallthrough
          case p[i] >= 'A' && p[i] < 'N':
               p[i] = p[i] + 13
          case p[i] >= 'n' && p[i] <= 'z':
               fallthrough
          case p[i] >= 'N' && p[i] <= 'Z':
               p[i] = p[i] - 13
          }
     }
     return leng, nil
}


func main() {
     s := strings.NewReader(
          "Lbh penpxrq gur pbqr!")
     r := rot13Reader{s}
     io.Copy(os.Stdout, &r)
}
复制代码

Exercise: Equivalent Binary Trees

复制代码
package main

import (
     "tour/tree"
     )

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
     if t == nil {
          return
     }
    
     Walk(t.Left, ch)
     ch <- t.Value
     Walk(t.Right, 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 func() {
          Walk(t1, ch1)
          ch1 <- 0
     }()
    
     go func() {
          Walk(t2, ch2)
          ch2 <- 0
     }()
    
     for {
          t1 := <-ch1
          t2 := <-ch2
          if t1 == 0 && t2 == 0 {
               return true;
          }
         
          if t1 == t2 {
               continue;
          } else {
               return false;
          }
     }
     return true
}

func main() {
     ch := make(chan int)
     go func() {
          Walk(tree.New(1), ch)
          ch <- 0
     }()
    
     for {
          t := <-ch
          if t == 0 {
               break;
          }
          println(t)
     }
    
     println(Same(tree.New(1), tree.New(2)))
}
复制代码

Exercise: Web Crawler

复制代码
package main

import (
     "fmt"
     "sync"
)

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)
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, out chan string, end chan bool) {
     if depth <= 0 {
          end <- true
          return
     }

     if _, ok := crawled[url]; ok {
          end <- true
          return
     }
     crawledMutex.Lock()
     crawled[url] = true
     crawledMutex.Unlock()

     body, urls, err := fetcher.Fetch(url)
     if err != nil {
          out <- fmt.Sprintln(err)
          end <- true
          return
     }

     out <- fmt.Sprintf("found: %s %q\n", url, body)
     subEnd := make(chan bool)
     for _, u := range urls {
          go Crawl(u, depth-1, fetcher, out, subEnd)
     }

     for i := 0; i < len(urls); i++ {
          <- subEnd
     }

     end <- true
}

var crawled = make(map[string]bool)
var crawledMutex sync.Mutex

func main() {
     out := make(chan string)
     end := make(chan bool)

     go Crawl("http://golang.org/", 4, fetcher, out, end)
     for {
          select {
          case t := <- out:
               fmt.Print(t)
          case <- end:
               return
          }
     }
}


// 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/",
          },
     },
}
复制代码
目录
相关文章
|
JavaScript Go 前端开发
|
14天前
|
Go
go语言中的数据类型
go语言中的数据类型
13 0
|
20天前
|
Go 开发者
掌握Go语言:Go语言结构体,精准封装数据,高效管理实体对象(22)
掌握Go语言:Go语言结构体,精准封装数据,高效管理实体对象(22)
|
20天前
|
安全 Go
掌握Go语言:Go语言通道,并发编程的利器与应用实例(20)
掌握Go语言:Go语言通道,并发编程的利器与应用实例(20)
|
20天前
|
存储 缓存 安全
掌握Go语言:Go语言中的字典魔法,高效数据检索与应用实例解析(18)
掌握Go语言:Go语言中的字典魔法,高效数据检索与应用实例解析(18)
|
20天前
|
Go
使用Go语言发邮件
使用Go语言发邮件
20 2
|
1月前
|
缓存 安全 Java
Go语言小细节
Go语言小细节
36 0
|
20天前
|
存储 安全 Go
掌握Go语言:Go语言类型转换,无缝处理数据类型、接口和自定义类型的转换细节解析(29)
掌握Go语言:Go语言类型转换,无缝处理数据类型、接口和自定义类型的转换细节解析(29)
|
1天前
|
数据采集 存储 Go
使用Go语言和chromedp库下载Instagram图片:简易指南
Go语言爬虫示例使用chromedp库下载Instagram图片,关键步骤包括设置代理IP、创建带代理的浏览器上下文及执行任务,如导航至用户页面、截图并存储图片。代码中新增`analyzeAndStoreImage`函数对图片进行分析和分类后存储。注意Instagram的反爬策略可能需要代码适时调整。
使用Go语言和chromedp库下载Instagram图片:简易指南
|
4天前
|
API Go
使用Go语言通过API获取代理IP并使用获取到的代理IP
使用Go语言通过API获取代理IP并使用获取到的代理IP

热门文章

最新文章