直接使用key获取value,key不存在的时候返回默认值,不会崩溃
mapIdName := map[string]string{}
name := mapIdName["123"]
map的元素是指针
type User struct{
UserId string
UserNo int64
}
type Group struct{
GroupMember map[string]*User
}
func main(){
myGroup := Group{}
if (nil == myGroup.GroupMember){
myGroup.GroupMember = make(map[string]*User) //要初始化
}
myGroup.GroupMember["1001"] = &User{UserId : "1001", UserNo : 10}
myGroup.GroupMember["1002"] = &User{UserId : "1002", UserNo : 12}
var othermap map[string]*User
othermap = myGroup.GroupMember //拷贝了map,但是map中的元素,还是共用一份
othermap["1002"].UserNo = 18 //修改了othermap,其实myGroup也被修改了,浅拷贝
heGroup := map[string]User{}
user1 := User{UserId : "1003", UserNo : 13}
user2 := User{UserId : "1004", UserNo : 14}
heGroup["1003"] = user1
heGroup["1004"] = user2
user3 := heGroup["1003"] //只是复制了一份user2,修改user3并不影响user2
user3.UserNo = 23
}