golang map探究

map的定义

map[KeyType]ValueType

KeyType为键的类型,ValueType为值的类型

map 初始化

    m1 := make(map[int]int)
    fmt.Println(m1) // map[]
    m2 := make(map[int]int,1)

make初始化的时候,可以不指定map容量,也可以指定容量

判断map是否存在某个值

package main

import "fmt"
  
func main() {
    m1 := make(map[int]int)
    m1[1] = 1
    m1[2] = 2
    v, ok := m1[1] // 返回两个值,后面的bool值就是判断map是否存在 1 这个值
    if ok {
        fmt.Println(v)
    } else {
        fmt.Println("without this key")
    }
}

Map的value赋值

package main

import (
    "fmt"
)

type S struct {
    s string
}

func main() {
    intmap := make(map[int]int, 0)
    intmap[1] = 1
    fmt.Println(intmap[1])  //1
    intmap[1] = 2
    fmt.Println(intmap[1])  //2

    structMap := make(map[int]S, 0)
    tmps := S{s: "tmp1"}
    structMap[1] = tmps
    fmt.Println(structMap[1])   //tmp1
    structMap[1].s = "tmp2"
    fmt.Println(structMap[1])   //cannot assign to struct field structMap[1].s in map
}

报错原因:map[int]S的value是一个Student结构值,所以当structMap[1].s = "tmp2"是一个值拷贝过程。而structMap[1]则是一个值引用。那么值引用的特点是 只读 。

修改方式1:

    tmps1 := structMap[1]
    tmps1.s = "tmp2"
    structMap[1] = tmps1
    fmt.Println(structMap[1])

先做一次值拷贝,做出一个tmps1副本,然后修改该副本,然后再次发生一次值拷贝复制回去,structMap[1] = tmps1,但是这种会在整体过程中发生2次结构体值拷贝࿰

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值