👩💻 Join our community of thousands of amazing developers!
[筆記] Go:Nil Map Posted on Jul 14, 2022 by LT package main import ( "fmt" ) func main() { var m map[string]int fmt.Println(m["test"]) m["test"]++ fmt.Println(m["test"]) } 上面這段code的輸出為0,然後panic。 在這個例子,m是一個nil map。在Go中,對nil map的有一些操作是”nil safe”的: len(m): 0 m[key] return the zero value for the value type if key is not in the map return the value assoiated with the key if key is in the map 利用第二個性質,假如是empty map的話,我們可以有像是python的defaultdict的應用。 package main import ( "fmt" ...