本章的三個例子來源與無聞老師的課程,很是感謝!閉包
所謂坑就是那些明明知道,但仍是容易犯錯,一旦犯錯,很久還查不出來的問題.app
通常你們都知道go中slice時會擴容的,在 append 時必定要寫成s = append(s, var) 的形式,可是仍是會容易犯錯,好比下面本想打印s擴容先後的值:code
package main import ( "fmt" ) func testAppend(s []string) { s = append(s, "1") // 注意參數的值拷貝特性 } func main() { s := make([]string, 0) fmt.Println(s) // [] testAppend(s) fmt.Println(s) // [] }
正確的用法應該是:orm
package main import ( "fmt" ) func testAppend(s []string) []string { return append(s, "1") } func main() { s := make([]string, 0) fmt.Println(s) // [] s = testAppend(s) fmt.Println(s) // [1] }
WTF "Mon Jan _2 15:04:05 2006"字符串
package main import ( "fmt" "time" ) func main() { now := time.Now() fmt.Println(now) // 2018-10-25 22:09:55.6575643 +0800 CST m=+0.005982101 fmt.Println(now.Format(time.ANSIC)) // Thu Oct 25 22:09:55 2018 fmt.Println(now.Format("Mon Jan _2 15:04:05 2006")) // Thu Oct 25 22:09:55 2018 fmt.Println(now.Format("Mon Jan _2 15:04:06 2006")) // Thu Oct 25 22:09:18 2018 } // 注意到了沒,時間格式化的時候直接使用字符串,若是字符串和time包定義的常量不同,會返回錯誤的時間,可是卻沒有任何提示
package main import ( "bufio" "fmt" "os" ) func main() { str := []string{"a", "b", "c"} for _, s := range str { go func() { fmt.Println(s) // 閉包引用的是地址,打印結果是隨機的 }() } inputReader := bufio.NewReader(os.Stdin) inputReader.ReadString('\n') }
正確的方式應該是input
func main() { str := []string{"a", "b", "c"} for _, s := range str { go func(s string) { fmt.Println(s) }(s) } inputReader := bufio.NewReader(os.Stdin) inputReader.ReadString('\n') }