Cannot assign to struct field in a map

后端 未结 2 612
小鲜肉
小鲜肉 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:16

    What I ended up doing to use my struct map in a loop was the following:

    type testStruct struct {
      a string
      b int
    }
    
    func main() {
      mapTest := make(map[string]testStruct)
      abc := [3]string{"a", "b", "c"}
    
      for i := 0; i < len(abc); i++ {
        var temp testStruct
        temp.a = abc[i]
        temp.b = i
        mapTest[abc[i]] = temp
      }
    
      fmt.Println(mapTest)
    }
    

    Output should be:

    map[b:{b 1} c:{c 2} a:{a 0}]
    

    It's not appending, but should work to assign multiple values to a struct map, alternatively you could do the following and allow the map to reference its own values:

    func main() {
      mapTest := make(map[string]testStruct)
    
      abc := [3]string{"a", "b", "c"}
      for i := 0; i < len(abc)*2; i++ {
        temp := mapTest[abc[i%3]]
        temp.a = abc[i%3]
        temp.b = temp.b + i
        mapTest[abc[i%3]] = temp
      }
    
      fmt.Println(mapTest)
    }
    

    Which should output:

    map[a:{a 3} b:{b 5} c:{c 7}]
    

    Note that no errors are raised when we reference an empty struct value, this is because when we initialize our struct, its values start out as empty values but not nil (0 for int, "" for string, etc.)

提交回复
热议问题