【发布时间】:2019-01-21 18:59:07
【问题描述】:
我正在使用 fmt.Sscan 将字符串转换为任何类型,这就是我正在做的事情:
package main
import (
"fmt"
"reflect"
)
func test() interface{} {
return 0
}
func main() {
a := test() // this could be any type
v := "10" // this could be anything
fmt.Println(reflect.TypeOf(a), reflect.TypeOf(&a))
_, err := fmt.Sscan(v, &a)
fmt.Println(err)
}
此代码失败,因为Sscan 不接受接口作为第二个值:can't scan type: *interface {}。 demo
我觉得最奇怪的是第一个 print 打印的是:int *interface {},是 int 还是 interface?
如何将a 断言为正确的类型(它可以是任何原始类型)?有没有不包含巨大 switch 语句的解决方案?
谢谢。
【问题讨论】:
-
您几乎从不需要指向接口的指针。您很可能想要一个具有底层指针类型的
interface{}类型值,例如*int. -
@ThunderCat 问题是:
convert a string to any type。