dongxun5349 2013-02-27 16:43
浏览 36
已采纳

运行时错误:“在nil映射中分配给条目”

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 in nil map");

I attempt to make an array of Maps, with each Map containing two indicies, a "Id" and a "Investor". My code looks like this:

for _, row := range rows {
        var inv_ids []string
        var inv_names []string

        //create arrays of data from MySQLs GROUP_CONCAT function
        inv_ids = strings.Split(row.Str(10), ",")
        inv_names = strings.Split(row.Str(11), ",")
        length := len(inv_ids);

        invs := make([]map[string]string, length)

        //build map of ids => names
        for i := 0; i < length; i++ {
            invs[i] = make(map[string]string)
            invs[i]["Id"] = inv_ids[i]
            invs[i]["Investor"] = inv_names[i]
        }//for

        //build Message and return
        msg := InfoMessage{row.Int(0), row.Int(1), row.Str(2), row.Int(3), row.Str(4), row.Float(5), row.Float(6), row.Str(7), row.Str(8), row.Int(9), invs}
        return(msg)
    } //for

I initially thought something like below would work, however that did not fix the issue either. Any ideas?

invs := make([]make(map[string]string), length)
  • 写回答

1条回答 默认 最新

  • dskvfdxgdo2422392 2013-02-27 17:15
    关注

    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
    ", a[i])
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度