Runtime error: “assignment to entry in nil map”

前端 未结 1 712
陌清茗
陌清茗 2021-01-04 04:02

I\'m trying to create a slice of Maps. Although the code compiles fine, I get the runtime error below:

mapassign1: runtime·panicstring(\"assignment to entry          


        
相关标签:
1条回答
  • 2021-01-04 04:35

    You are trying to create a slice of maps; consider the following example:

    http://play.golang.org/p/gChfTgtmN-

    package main
    
    import "fmt"
    
    func main() {
        a := make([]map[string]int, 100)
        for i := 0; i < 100; i++ {
            a[i] = map[string]int{"id": i, "investor": i}
        }
        fmt.Println(a)
    }
    

    You can rewrite these lines:

    invs[i] = make(map[string]string)
    invs[i]["Id"] = inv_ids[i]
    invs[i]["Investor"] = inv_names[i]
    

    as:

    invs[i] = map[string]string{"Id": inv_ids[i], "Investor": inv_names[i]}
    

    this is called a composite literal.

    Now, in a more idiomatic program, you'd most probably want to use a struct to represent an investor:

    http://play.golang.org/p/vppK6y-c8g

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    type Investor struct {
        Id   int
        Name string
    }
    
    func main() {
        a := make([]Investor, 100)
        for i := 0; i < 100; i++ {
            a[i] = Investor{Id: i, Name: "John" + strconv.Itoa(i)}
            fmt.Printf("%#v\n", a[i])
        }
    }
    
    0 讨论(0)
提交回复
热议问题