为什么映射中的键和值共享相同的内存地址?

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

Why do keys and values from a map share the same memory address?

问题

我注意到当在映射中迭代键和值时,键和值共享相同的内存地址。你可以在这里看到:

package main

import "fmt"

func main() {
	myMap := map[string]string{
		"hello": "world",
		"how":   "are",
		"you":   "today?",
	}
	for key, value := range myMap {
		fmt.Printf("Key: %p %v\n", &key, key)
		fmt.Printf("Value: %p %v\n", &value, value)
		fmt.Println("---")
	}
}

... 输出结果为 ...

Key: 0xc00009e210 hello
Value: 0xc00009e220 world
---
Key: 0xc00009e210 how
Value: 0xc00009e220 are
---
Key: 0xc00009e210 you
Value: 0xc00009e220 today?
---

为什么会这样呢?

英文:

I notice that when iterating across keys and values in a map, they keys and values all share the same memory address. You can see that here:

package main

import "fmt"

func main() {
	myMap := map[string]string{
		"hello": "world",
		"how":   "are",
		"you":   "today?",
	}
	for key, value := range myMap {
		fmt.Printf("Key: %p %v\n", &key, key)
		fmt.Printf("Value: %p %v\n", &value, value)
		fmt.Println("---")
	}
}

... which outputs ...

Key: 0xc00009e210 hello
Value: 0xc00009e220 world
---
Key: 0xc00009e210 how
Value: 0xc00009e220 are
---
Key: 0xc00009e210 you
Value: 0xc00009e220 today?
---

Why is that?

答案1

得分: 6

你没有获取映射中值的地址。实际上,在Go语言中,映射元素是不可寻址的。你获取的是局部循环变量的地址,称为"key"和"value"。它们在每次循环迭代中不会改变,因为没有理由让它们改变(它们被重用)。

参考:

为什么Go禁止获取(&)映射成员的地址,但允许获取(&)切片元素的地址?

英文:

You are not taking the address of the values in the map. Actually, map elements are not addressable in Go. You are taking the addresses of the local loop variables, called "key" and "value". Those don't change across each loop iteration, because there is no reason for them to (they are re-used).

See:

Why does Go forbid taking the address of (&) map member, yet allows (&) slice element?

huangapple
  • 本文由 发表于 2021年9月16日 12:37:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/69202411.html
匿名

发表评论

匿名网友

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

确定