dsz90288
2018-10-01 22:16
浏览 26
已采纳

无法分配给struct字段/分配给nil映射中的条目[重复]

This question already has an answer here:

Does anyone have any idea why this doesn't work?

I've been racking my brain for about 4 hours now. I cannot make it work.

In my opinion, I'm trying to do the same thing twice. I'm making a map of a field in a struct, and then I'm doing it again on another field in a different struct.

If I try to make the map. It fails with: "cannot assign to struct field. Bet.Events["one"].Runners in map".

So if I remove the make, and just try to assign it, I get: "assignment to entry in nil map"

https://play.golang.org/p/kRcXoyO-8FN

var Bet BetStruct

type BetStruct struct {
    Events     map[string]Event
}

type Event struct {
    Name       string
    Runners    map[int]Runner
}

type Runner struct {
    Name       string
}

func main(){

    // == THIS WORKS FINE ==
    Bet.Events = make(map[string]Event)

    Bet.Events["one"] = Event{
        Name: "first",
    }
    Bet.Events["two"] = Event{
        Name: "second",
    }

    // == THIS DOES NOT WORK ==
    Bet.Events["one"].Runners = make(map[int]Runner)

    Bet.Events["one"].Runners[0] = Runner{
         Name:  "Jeff",
    }
}
</div>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案:

  • 如何在Go中更新地图值 1个答案

    有人知道为什么这不起作用吗? \ n

    我已经绞尽脑汁了大约4个小时。 我无法使其正常工作。

    在我看来,我试图做两次相同的事情。 我正在制作一个结构中的字段的映射,然后又在另一个结构中的另一个字段上进行了映射。

    如果我尝试制作该映射。 它失败并显示:“无法分配给struct字段。Bet.Events [“ one”]。地图中的赛跑者”。

    因此,如果我删除了make,并尝试分配它, 我得到:“在零地图中分配条目”

    https://play.golang.org/p/kRcXoyO-8FN

      var Bet BetStruct 
     
    type BetStruct struct {
    事件地图[string] 事件
    } 
     
    type事件结构{
    名称字符串
     Runners地图[int] Runner 
    } 
     
    type Runner结构{
    名称字符串
    } 
     
    func main(){
      
     // ==这很不错== 
     Bet.Events = make(map [string] Event)
     
     Bet.Events [“ one”] =事件{
    名称:“ first”,
      } 
     Bet.Events [“ two”] =事件{
    名称:“ second”,
    } 
     
     // ==不起作用== 
     Bet.Events [“ one”]。 跑步者= make(map [int] Runner)
     
     Bet.Events [“ one”]。跑步者[0] =跑步者{
    名称:“ Jeff”,
    } 
    } 
        
     
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doudang1890 2018-10-01 22:48
    已采纳

    The default value for map is nil (before or without make(map))

    You set a default value for Runners in this code:

    Bet.Events["one"] = Event{
        Name: "first",
    }
    

    So, Runners wasn't defined clearly and was setting to nil.

    Structs are mutable expect map elements. You cannot reinitialize map element Bet.Events["one"] because is not addressable.

    You need to do:

    Bet.Events["one"] = Event{
        Name: "first",
        Runners: make(map[int]Runner),
    }
    

    Thanks @icza for marking errors in the text

    打赏 评论

相关推荐 更多相似问题