How to modify map in go

huangapple go评论83阅读模式
英文:

How to modify map in go

问题

我正在尝试修改"loopback"的IP地址,但似乎无法直接访问该元素。

addrs["loopback"][0] = byte(2) //无法对addrs["loopback"][0]赋值

在Go语言中,我该如何实现这个功能?

package main

import "fmt"

type IPAddr [4]byte

func main() {
	addrs := map[string]IPAddr{
		"loopback":  {127, 0, 0, 1},
		"googleDNS": {8, 8, 8, 8},
	}
	addrs["loopback"][0] = byte(2)
	for n, a := range addrs {
		fmt.Printf("%v: %v\n", n, a)
	}
}
英文:

I am trying to modify the IPAddr for the "loopback", but it seems cannot access the element directly.

addrs["loopback"][0] = byte(2) //cannot assign to addrs["loopback"][0]

How can I do it within go?

package main

import "fmt"

type IPAddr [4]byte

func main() {
	addrs := map[string]IPAddr{
		"loopback":  {127, 0, 0, 1},
		"googleDNS": {8, 8, 8, 8},
	}
	addrs["loopback"][0] = byte(2)
	for n, a := range addrs {
		fmt.Printf("%v: %v\n", n, a)
	}
}

答案1

得分: 3

因为映射值不可寻址,所以你需要重新分配整个值:

addr := addrs["loopback"]
addr[0] = 2
addrs["loopback"] = addr

playground示例

如果你将映射值类型更改为*IPAddr,那么赋值语句

addrs["loopback"][0] = 2

就可以工作了。在这种情况下,代码是将值分配给映射所指向的值。这个值是可寻址的。

playground示例

英文:

Because map values are not addressable, you need to reassign the entire value:

addr := addrs["loopback"]
addr[0] = 2
addrs["loopback"] = addr

playground example

If you change the map value type to *IPAddr, then the assignment

addrs["loopback"][0] = 2

works. In this case, the code is assigning to a value pointed to by the map. This value is addressable.

playground example

huangapple
  • 本文由 发表于 2015年7月26日 11:51:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/31633453.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定