• 欢迎访问周知博客,每周记录新知识
  • 祝各位学得开心!!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

go问题(map的值赋值)

go问题集 admin 2个月前 (03-10) 73次浏览 0个评论

下面代码输出什么?

type Math struct {
	x, y int
}

var m = map[string]Math{
	"foo": Math{2, 3},
}

func main() {
	m["foo"].x = 4
	fmt.Println(m["foo"].x)
}
A. 4
B. compilation error

答案解析:
参考答案及解析:B,编译报错 cannot assign to struct field m[“foo”].x in map。错误原因:对于类似 X = Y的赋值操作,必须知道 X 的地址,才能够将 Y 的值赋给 X,但 go 中的 map 的 value 本身是不可寻址的。

有两个解决办法:

a.使用临时变量

type Math struct {
	x, y int
}

var m = map[string]Math{
	"foo": Math{2, 3},
}

func main() {
	tmp := m["foo"]
	tmp.x = 4
	m["foo"] = tmp
	fmt.Println(m["foo"].x)
}

b.修改数据结构

type Math struct {
	x, y int
}

var m = map[string]*Math{
	"foo": &Math{2, 3},
}

func main() {
	m["foo"].x = 4
	fmt.Println(m["foo"].x)
	fmt.Printf("%#v", m["foo"]) 
}

周知博客, 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:go问题(map的值赋值)
喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址