SoFunction
Updated on 2025-03-05

Golang Map value Unaddressable use pointer type instead of example explanation

Golang Map element addressing

package main
import "fmt"
type UserInfo struct {
    Uid      string `json:"uid"`
    UserName string `json:"user_name"`
    Sex      int    `json:"sex"`
}
func main() {
    var user = make(map[string]UserInfo)
    uid := "0001"
    user[uid] = UserInfo{
        Uid:      uid,
        UserName: "jack",
        Sex:      1,
    }
    user[uid].UserName="polly"
    (user[uid])
}

The above code reported an error:./:19:20: cannot assign to struct field user[uid].UserName in map

The reason is that the map element cannot be addressed, which means that user[uid].UserName can be obtained, but it cannot be modified.

Solution Use pointer map

When a map in golang gets the value through the key, this value is unaddressable because the map will be dynamically expanded. After expansion, the map's value will be memory migrated and its address changes, so this value cannot be addressed. That is the reason for the above problems. The expansion of map is different from slices. Then map itself is a reference type. When used as a formal parameter or return parameter, it is passed a copy of the value, and the value is the address. This address will not be changed during expansion. The expansion of slice will lead to address changes.

package main
import "fmt"
type UserInfo struct {
    Uid      string `json:"uid"`
    UserName string `json:"user_name"`
    Sex      int    `json:"sex"`
}
func main() {
    var user = make(map[string]*UserInfo)
    uid := "0001"
    user[uid] = &UserInfo{
        Uid:      uid,
        UserName: "jack",
        Sex:      1,
    }
    user[uid].UserName="polly"
    (user[uid])
}

The above is the detailed explanation of the example of using pointer type instead of the non-addressable example of Golang Map value. For more information about addressing the addressing of Golang Map value, please pay attention to my other related articles!