通过匿名结构键进行地图查找(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 }]stringQuestion: 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
更多推荐
发布评论