通过接口{}传递的sql.NullFloat64对象调用方法会引发错误。

huangapple go评论76阅读模式
英文:

Calling methods on sql.NullFloat64 passed in through interface{} throws error

问题

我有一个简单的函数,代码如下:

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 可以是 NullFloat64NullInt64 类型。如果 numberNullFloat64 类型,我调用 number.Float64 并将其作为 Float64 类型的值返回。但是,如果我在一个以 interface{} 类型的参数接收 number 的函数中尝试调用相同的方法,就会出现编译错误:

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

在函数内部,如果我调用 reflect.TypeOf(number),它会返回 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

得分: 0

在类型切换中,将数字的实际值(无论其类型如何)分配给v。问题在于在分配给newNumber时重新使用了number,这仍然是进入case sql.NullFloat64时的同一个旧的interface{}类型,而v的类型是number中的值,因此您希望将其用于赋值。

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  
}
英文:

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  
}

huangapple
  • 本文由 发表于 2015年8月11日 02:36:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/31926732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定