通过匿名结构键进行地图查找(Map lookup via anonymous struct key)

编程入门 行业动态 更新时间:2024-10-26 02:29:36
通过匿名结构键进行地图查找(Map lookup via anonymous struct key)

我有以下map其键类型是匿名struct :

var data map[struct{ pID, bID int }]string

问题: 如何构建实际获取/设置data值的密钥

我试过这些,这些都会导致编译错误:

data[{1,2}] = "ok" data[{pID: 1, bID 2}] = "ok"

似乎我不能在没有类型名称的情况下形成复合文字,但是没有类型名称。


这个相关问题使用任意struct作为map的 ,但不使用密钥

匿名结构作为地图的值

I have the following map whose key type is an anonymous struct:

var data map[struct{ pID, bID int }]string

Question: How would I go about constructing a key to actually get/set a value in data?

I've tried these, which all result in compiler errors:

data[{1,2}] = "ok" data[{pID: 1, bID 2}] = "ok"

It seems I cannot form a compound literal without having the type name, but there is no type name.


This related question uses an anymous struct as the value of a map, but not the key:

Anonymous struct as value to a map

最满意答案

您也可以创建匿名密钥,如下所示:

func main() { data := map[struct{ pID, bID int }]string{} key := struct{pID, bID int}{1, 2} data[key] = "abc" data[struct{pID, bID int}{3, 4}] = "cha cha cha" fmt.Printf("%+v\n\n", data) fmt.Printf("'%s' '%s'\n", data[key], data[struct{pID, bID int}{3, 4}]) }

完整档案: https : //play.golang.org/p/2q11qiwxuI

You can create anonymous keys as well, something like this:

func main() { data := map[struct{ pID, bID int }]string{} key := struct{pID, bID int}{1, 2} data[key] = "abc" data[struct{pID, bID int}{3, 4}] = "cha cha cha" fmt.Printf("%+v\n\n", data) fmt.Printf("'%s' '%s'\n", data[key], data[struct{pID, bID int}{3, 4}]) }

Full file: https://play.golang.org/p/2q11qiwxuI

更多推荐

本文发布于:2023-07-15 05:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110620.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:结构   地图   Map   lookup   struct

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!