golang map初始化的坑

Map nil

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)
}
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)
    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)   
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注