英文:
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
如果你将映射值类型更改为*IPAddr,那么赋值语句
addrs["loopback"][0] = 2
就可以工作了。在这种情况下,代码是将值分配给映射所指向的值。这个值是可寻址的。
英文:
Because map values are not addressable, you need to reassign the entire value:
addr := addrs["loopback"]
addr[0] = 2
addrs["loopback"] = addr
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论