英文:
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
可以是 NullFloat64
或 NullInt64
类型。如果 number
是 NullFloat64
类型,我调用 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论