Can not assign to pair in a map

前端 未结 3 388
一生所求
一生所求 2020-12-21 00:16

I have the following pair defined in my go program

type pair struct {
  a float64
  b float64
}

Then I create a map:

dictio         


        
3条回答
  •  伪装坚强ぢ
    2020-12-21 00:29

    In order to assign a value to a struct field, that struct must be "addressable". Addressability is covered in the "Address Operators" section of the language specification.

    Map values aren't addressable to leave map implementations the freedom to move values around in memory as needed. Because map values aren't addressable, you you can't use a selector (.) operator on the value to assign to the struct field. If you use a pointer type as the map value, i.e. map[string]*pair, the pointer indirection satisfies the addressability requirement.

    dict := make(map[string]*pair)
    dict["xxoo"] = &pair{5.0, 2.0}
    dict["xxoo"].b = 5.0
    

    If you are working with values, you need to copy the existing value via assignment, or supply an entirely new value:

    dict := make(map[string]pair)
    dict["xxoo"] = pair{5.0, 2.0}
    
    // copy the value, change one field, then reassign
    p := dict["xxoo"]
    p.b = 5.0
    dict["xxoo"] = p
    
    // or replace the value in full
    dict["xxoo"] = pair{5.0, 5.0}
    

提交回复
热议问题