Cannot assign to struct field in a map

后端 未结 2 642
小鲜肉
小鲜肉 2021-02-01 14:00

I have the data structure like this:

type Snapshot struct {
  Key   string
  Users []Users
}

snapshots := make(map[string] Snapshot, 1)

// then did the initial         


        
2条回答
  •  你的背包
    2021-02-01 14:30

    First, for this question, the solution in this post Why do I get a "cannot assign" error when setting value to a struct as a value in a map? works perfectly fine.

    Then, finally figured out why after I already changed to use pointer my case still doesn't work, refer to the below very simple code:

    a := make([]int, 3)
    fmt.Println(len(a))
    
    b := make(map[string]string, 3)
    fmt.Println(len(b))
    

    What do think the output will be? I simply thought it is all would be: 3, but actually for the map, the output will be 0

    Then later in the map initialization process, i used a for loop and with this value len(snapshots), that means the initialization process will never get run...

    Yea, that is the reason.

提交回复
热议问题