Why map literals in Go allow overwriting keys when using a function call instead of a literal?

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

Why map literals in Go allow overwriting keys when using a function call instead of a literal?

问题

package main

import "fmt"

func main() {
	blaa := map[string]string{
		"key":    "value",
		getKey(): "value2", // 用 "key" 替换 getKey() 会导致编译时错误。
	}
	fmt.Println("Hello, " + blaa["key"])
}

func getKey() string {
	return "key"
}

运行上述程序将打印 "Hello, value2"。在这里尝试运行:https://go.dev/play/p/s92LaaNc3n4

虽然我可以看到键被覆盖了,但我想知道为什么这不会在运行时引发 panic?使用两个字符串字面值 "key" 会导致编译时错误,这是预期的行为。

英文:
package main

import "fmt"

func main() {
	blaa := map[string]string{
		"key":    "value",
		getKey(): "value2", //replacing getKey() with "key" results in compile time error.
	}
	fmt.Println("Hello, " + blaa["key"])
}

func getKey() string {
	return "key"
}

Running the above program will print "Hello, value2". Try it here https://go.dev/play/p/s92LaaNc3n4

While I can see the key gets overwritten, I'm wondering why this doesn't panic at runtime? Using two string literals "key" will result in a compilation time error, which is the expected behaviour.

答案1

得分: 9

一个形式为的地图文字:

blaa := map[string]string{
        "key":    "value",
        "key": "value2", 
    }

是一个编译时错误,因为所有的值在编译时都是已知的,并且具有重复键的地图是无效的地图文字。

以下是在运行时计算的:

blaa := map[string]string{
        "key":    "value",
        getKey(): "value2", 
    }

这创建了一个具有一个元素的地图文字,然后使用给定函数的结果设置第二个元素。

重写键是一个有效的操作,这就是为什么它不会引发错误的原因。

英文:

A map literal of the form:

blaa := map[string]string{
        "key":    "value",
        "key": "value2", 
    }

is a compile-time error, because all values are known at compile time, and a map with duplicate keys is an invalid map literal.

The following is computed at runtime:

blaa := map[string]string{
        "key":    "value",
        getKey(): "value2", 
    }

This creates a map literal with one element, and then sets the second element using the result of the given function.

Rewriting a key is a valid operation, that's why it does not panic.

huangapple
  • 本文由 发表于 2023年3月13日 09:54:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75717483.html
匿名

发表评论

匿名网友

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

确定