go tour 學習筆記

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

做了幾個例子,

1. 2位精度內逼近2開方的。

package mainimport ("fmt""math")func Sqrt(x float64) float64 {b:=1.00for z:=1.00;z<math.Trunc(math.Sqrt(2)*math.Pow10(2))/math.Pow10(2);z+=0.01 {     b = z - (z*z-x)/(2*z)}   return b}func main() {fmt.Println(Sqrt(2))fmt.Println(math.Trunc(math.Sqrt(2)*math.Pow10(2))/math.Pow10(2))        fmt.Println(math.Sqrt(2))}

 

2. 這個例子也很好玩可以看自己的平台

package mainimport ("fmt""runtime")func main() {fmt.Print("Go runs on ")switch os := runtime.GOOS; os {case "darwin":fmt.Println("OS X.")case "linux":fmt.Println("Linux.")default:// freebsd, openbsd,// plan9, windows...fmt.Printf("%s.", os)}}

 

3. 統計詞頻的

package mainimport ("golang.org/x/tour/wc""strings")func WordCount(s string) map[string]int {m := make(map[string]int)for _,value:=  range strings.Fields(s) {m[value]+=1}return m}func main() {wc.Test(WordCount)}

 

4.自己最滿意的一個fibonacci,用閉包實現

package mainimport "fmt"// fibonacci is a function that returns// a function that returns an int.func fibonacci() func() int {f_slice := make([]int, 2)f_slice = []int{0,1}f_index :=0return func() int {if f_index >1 {     f_slice = append(f_slice,f_slice[f_index-1]+f_slice[f_index-2])}f_index +=1return f_slice[f_index-1]}}func main() {f := fibonacci()for i := 0; i < 10; i++ {fmt.Println(f())}}

 

5.ip地址轉換

package mainimport "fmt"type IPAddr [4]byte// TODO: Add a "String() string" method to IPAddr.func (m IPAddr) String() string {var ret stringfor i, value := range m {if i==0 { ret +=fmt.Sprintf("%v",value)} else {ret += fmt.Sprintf(".%v",value)}}return ret}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)}}

 

明天接著更

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.