dragon456101 2016-10-15 00:03
浏览 34
已采纳

通过匿名结构键查找地图

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:

  • 写回答

1条回答 默认 最新

  • duancilan5124 2016-10-15 00:35
    关注

    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
    
    ", data)
    
        fmt.Printf("'%s' '%s'
    ", data[key], data[struct{pID, bID int}{3, 4}])
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了