panic: assignment to entry in nil map


轉載自:https://github.com/kevinyan815/gocookbook/issues/7
golang中map是引用類型,應用類型的變量未初始化時默認的zero value是nil。直接向nil map寫入鍵值數據會導致運行時錯誤

panic: assignment to entry in nil map

看一個例子:

package main
const alphabetStr string = "abcdefghijklmnopqrstuvwxyz"
func main() {
  var alphabetMap map[string]bool
  for _, r := range alphabetStr {
    c := string(r)
    alphabetMap[c] = true
  }
}

運行這段程序會出現運行時從錯誤:

panic: assignment to entry in nil map

因為在聲明alphabetMap后並未初始化它,所以它的值是nil, 不指向任何內存地址。需要通過make方法分配確定的內存地址。程序修改后即可正常運行:

package main
import "fmt"
const alphabetStr string = "abcdefghijklmnopqrstuvwxyz"
func main() {
  alphabetMap := make(map[string]bool)
  for _, r := range alphabetStr {
    c := string(r)
    alphabetMap[c] = true
  }
  fmt.Println(alphabetMap["x"])
  alphabetMap["x"] = false
  fmt.Println(alphabetMap["x"])
}

關於這個問題官方文檔中解釋如下:

This variable m is a map of string keys to int values:
var m map[string]int
Map types are reference types, like pointers or slices, and so the value of m above is nil; it doesn’t point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don’t do that. To initialize a map, use the built in make function:
m = make(map[string]int)

同為引用類型的slice,在使用append 向nil slice追加新元素就可以,原因是append方法在底層為slice重新分配了相關數組讓nil slice指向了具體的內存地址

nil map doesn’t point to an initialized map. Assigning value won’t reallocate point address.
The append function appends the elements x to the end of the slice s, If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM