美文网首页
golang map的坑

golang map的坑

作者: 夜空一起砍猩猩 | 来源:发表于2020-05-29 10:35 被阅读0次

    当结构体的某个成员是map类型, 结构体初始化后map需要单独初始化,否则对map的操作会
    “panic: assignment to entry in nil map”

    import (
        "fmt"
    )
    
    //panic: assignment to entry in nil map
    type Param map[string]interface{}
    
    type Show struct {
        Param
    }
    
    func main() {
        s := new(Show)
        //s.Param["RMB"] = 10000 //panic: assignment to entry in nil map
        s.Param = map[string]interface{}{}
        s.Param = Param{}
        s.Param["RMB"] = 10000 
        fmt.Println(s)
    }
    

    当结构体的某个成员是指向map类型的指针类型, ,对map的操作可能会发生如下两种情况:
    1: map未初始化,通过s.Param["RMB"]访问,会导致"invalid operation: s.Param["RMB"] (type *Param does not support indexing)"
    2: map未初始化, 通过s.Param["RMB"]访问, 对该成员的访问会导致"panic: runtime error: invalid memory address or nil pointer "
    3: map已初始化,通过s.Param["RMB"]访,会导致"invalid operation: s.Param["RMB"] (type *Param does not support indexing)", 所以对改指针的指向值的访问需要解引用:

    (*s.Param)["RMB"] 
    
    package main
    import "fmt"
    
    type Param map[string]interface{}
    
    type Show struct {
        *Param
    }
    
    func main() {
        s := new(Show)
        // s.Param["RMB"] = 10000 //invalid operation: s.Param["RMB"] (type *Param does not support indexing)
       // (*s.Param)["RMB"] = 10000 //panic: runtime error: invalid memory address or nil pointer dereference
        p := Param{}
        s.Param = &p
        //s.Param["RMB"] = 100000 //s.Param["RMB"] (type *Param does not support indexing)
        (*s.Param)["RMB"] = 100000
        fmt.Println(s.Param)   
    }
    

    相关文章

      网友评论

          本文标题:golang map的坑

          本文链接:https://www.haomeiwen.com/subject/vrcxzhtx.html