dsu89430 2016-11-18 18:18
浏览 39
已采纳

错误:需要类型断言

I thought I have asserted (as far as I've learnt Go), but I keep getting this error cannot use readBack["SomePIN"] (type interface {}) as type string in argument to c.String: need type assertion

Here is my code (this snippet is from a Request Handler function and I'm using Echo Web framework and Tiedot NoSQL database)

// To get query result document, simply 
// read it [as stated in the Tiedot readme.md]
for id := range queryResult {
    readBack, err := aCollection.Read(id)
    if err != nil {
        panic(err)
    }
    if readBack["OtherID"] == otherID {
        if _, ok := readBack["SomePIN"].(string); ok {
            return c.String(http.StatusOK, readBack["SomePIN"])
        }
    }
}
  • 写回答

2条回答 默认 最新

  • dsqpx86002 2016-11-18 18:26
    关注

    You are asserting readBack["SomePIN"] as a string - in the if statement. That doesn't make any change to readBack["SomePIN"], however - it's still an interface{}. In Go, nothing ever changes type. Here's what will work:

    for id := range queryResult {
        readBack, err := aCollection.Read(id)
        if err != nil {
            panic(err)
        }
        if readBack["OtherID"] == otherID {
            if somePIN, ok := readBack["SomePIN"].(string); ok {
                return c.String(http.StatusOK, somePIN)
            }
        }
    }
    

    You were tossing the string value from your type assertion, but you want it. So keep it, as somePIN, and then use it.

    Final note - using the value, ok = interfaceVal.(type) syntax is a good practice. If interfaceVal turns out to be a non-string, you'll get value = "" and ok = false. If you eliminate the ok value from the type assertion and interfaceVal is a non-string, the program will panic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序