A tour of Go的疑問

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

Go 官網上給大家提供了很多練習,是學習Go的不錯的途徑,但是我遇到一個問題,這個練習中要求用Closure列印Fibonacci數列

http://tour.golang.org/moretypes/22

Exercise: Fibonacci closure


package main


import "fmt"


// fibonacci is a function that returns
// a function that returns an int.
/*func fibonacci() func() int {
x := 0
y := 1
z := 0
return func() int {
        z = x
x = y
y = x + y
return z
}
}*/


func fibonacci() func() int {
x := 0
y := 1
z := 0
return func() int {
z, x, y = x, y, x+y
return z
}
}


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

有兩個地方沒明白:1. main()裡的f沒有參數傳入,是怎麼實現不斷迭代的,也就是,當i = 0和 i = 1的時候,為什麼列印的結果會不一樣呢
2. 我在網上找到一種解法,就是沒注釋掉的,我不理解它和上面我注釋掉的方法之間的差別在哪,也就是

        z = x
x = y
y = x + y

和  z, x, y = x, y, x+y之間的差別

從執行的結果來看,它們是完全不一樣的


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.