[Go] 閱讀心得 不負責任翻譯 Golang Frequently Asked Questions (FAQ) PART4 END
https://golang.org/doc/faq 官方FAQ 提供一些有趣的資訊,很認真的試圖都理解一下,由於內容太多,拆成幾個部分來看。 PART4這裡有 Functions and Methods Control flow Packages and Testing Implementation Performance Changes from C --Functions and Methods-- Why do T and *T have different method sets? 接收到型態T的對象,有型態T所有的method,但如果是接收到型態*T,則會擁有型態T和型態*T的所有method。 如果interface裡面包含*T,那麼操作的行為會是pointer,如果是T,那操作的行為只能是value的處理方式。 如果是傳value,copy值之後,就跟原本被copy的部分沒關係了。 What happens with closures running as goroutines? func main() { done := make(chan bool) values := []string{"a", "b", "c"} for _, v := range values { go func() { fmt.Println(v) done 這個範例是在學GO蠻經典的例子,結論是永遠不要在gorutine裡面直接使用外面的變數。 因為goruntine宣告後並不是馬上建立的,可能等一下才建立,以及複數個gorutine建立起來可能沒有順序性,此時外面的變數已經不知道跑到哪裡去了。 有兩個比較直觀的解法,一個是每次都直接將變數傳入goruntine的function。 一個是傳入之前都先copy一份。(這個感覺跟每個與scope處理的範圍有關,比較不直覺。) --Control flow-- Does Go have the ?: operator? Go 沒有問號冒號的運算符號,請愛用if else 達成你的目標。 ...