doushe8577 2019-04-03 09:35
浏览 15

当我的值是结构类型时,如何填充map [string]接口{}?

I am wanting to build a JSON equivalent of the PurchaseOrder struct below:

type PurchaseOrder struct {
    State      string
    FsmName    string
    Supplier   string
    Receiver   string
    TradeItems map[string]PRTradeItem
}

type PRTradeItem struct {
    Quantity float64 `json:"quantity"`
    Supplier string  `json:"supplier"`
    Receiver string  `json:"receiver"`

    PricePerUnit float64 `json:"pricePerUnit"`
}

In order to do so, I did the following:

po := make(map[string]interface{})
po["Sender"] = "org2"
po["Receiver"] = "org1"
po["TradeItems"] = make(map[string]PRTradeItem)
po["TradeItems"]["sku1"] = PRTradeItem{Quantity: 100, Supplier: "org2", Receiver: "org1", PricePerUnit: 10.5}
poAsBytes, _ := JSON.Marshal(po)

The error that I get is:

invalid operation: po["TradeItems"]["sku1"] (type interface {} does not support indexing).

After looking around a bit, I added the following lines to the code and it worked.

internalMap, ok := po["TradeItems"].(map[string]PRTradeItem)
if !ok{

    panic("why???")
}
if ok{  
    internalMap["sku1"] = PRTradeItem{Quantity:100,Supplier:"org2", Receiver:"org1", PricePerUnit:10.5}
}

I don't quite understand what this line means

internalMap, ok := po["TradeItems"].(map[string]PRTradeItem)

Can someone please explain?

  • 写回答

2条回答 默认 最新

  • douan6931 2019-04-03 09:42
    关注

    I know the type of po["TradeItems"]. Please explain in-depth. Why should I assert?

    You do, but the compiler doesn't. Your po has type map[string]interface{}. So po["TradeItems"] in po["TradeItems"]["sku1"] returns an object of type interface{}, which you can't do anything useful with (not without reflection or type-assertions).

    Hence the need to hint the compiler with that type assertion.

    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)