doushun1870 2015-08-10 18:36
浏览 179
已采纳

通过interface {}传递的sql.NullFloat64上的调用方法抛出错误

I have a simple function that looks like this:

func convertToRealNum(number interface{}) interface{}{
  switch v := number.(type) { 
  default:
    log.Fatal("unexpected type %T", v)
  case sql.NullFloat64:
    newNumber := number.Float64
  case sql.NullInt64:
    newNumber := number.Int64
  }
  return newNumber 
}

number is either a NullFloat64 or a NullInt64. If number is the type NullFloat64, I call number.Float64 on it and get back the value of the number as a Float64. If I try to call the same thing inside a function that takes number as an argument that is an interface{} I get the compile error:

number.Float64 undefined (type interface {} has no field or method Float64)

Inside the function, if I call reflect.TypeOf(number) it'll return NullFloat64, so it knows what type it is, but I can't call that types methods.

  • 写回答

1条回答 默认 最新

  • dongwuzun4630 2015-08-10 18:42
    关注

    The actual value of number (whatever type it is) is assigned to v in the type switch. The problem is you're re-using number in the assignment to newNumber, that is still the same old interface{} when you go into the case sql.NullFloat64 that is the type of v which has the value of number in it so you'll want to use it for assignment.

    func convertToRealNum(number interface{}) interface{}{
     var newNumber interface{} 
     switch v := number.(type) { 
      default:
        log.Fatal("unexpected type %T", v)
      case sql.NullFloat64:
        newNumber = v.Float64
      case sql.NullInt64:
        newNumber = v.Int64
      }
      return newNumber  
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我这模型写的不对吗?为什么lingo解出来的下面影子价格这一溜少一个变量
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波