Golang的map可以使用任意类型的键和任意类型的值。

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

Golang map with any key type and any value type

问题

可以在Golang中创建一个具有任意键类型和任意值类型的映射。你可以像这样创建一个映射:

dict1 := make(map[interface{}]interface{})

希望对你有帮助!

英文:

can i create in golang a map with any key type and any value type ? , something like :

dict1 := map[interface]interface{}

Thanks a lot !

答案1

得分: 4

从键类型的语言规范中可以看到:

键类型的操作符==和!=必须完全定义。

因此,大多数类型都可以用作键类型,但是:

切片、映射和函数值是不可比较的,因此不能用作映射的键。

值类型可以是任何类型,包括anyinterface{}类型。

type mytype struct{}
type ss []string

_ = make(map[interface{}]interface{}) // 这样可以...
_ = make(map[any]any)                 // ... 语义上相同
_ = make(map[mytype]any)              // 甚至可以是结构体

_ = make(map[ss]any) // 失败:无效的映射键类型 ss

https://go.dev/play/p/OX_utGp8nfH

英文:

From the language spec for the key type:

> The comparison operators == and != must be fully defined for operands
> of the key type;

So most types can be used as a key type, however:

> Slice, map, and function values are not comparable

and thus cannot be used as a map-key.

The value type can be any or (any or interface{}) type.

type mytype struct{}
type ss []string

_ = make(map[interface{}]interface{}) // this works...
_ = make(map[any]any)                 // ... semantically the same
_ = make(map[mytype]any)              // even a struct

_ = make(map[ss]any) // FAILS: invalid map key type ss

https://go.dev/play/p/OX_utGp8nfH

huangapple
  • 本文由 发表于 2022年4月9日 01:45:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/71801244.html
匿名

发表评论

匿名网友

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

确定