String 如何使用带接口的Sscan
我正在使用String 如何使用带接口的Sscan,string,go,interface,String,Go,Interface,我正在使用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.T
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
不接受接口作为第二个值:无法扫描类型:*接口{}
我发现最奇怪的是第一次打印的是:int*interface{}
,它是int还是interface
如何将a
断言为正确的类型(它可以是任何基元)?有没有一个解决方案不包括一个巨大的开关语句
谢谢。以下是如何将字符串转换为
fmt
包支持的任何类型的值:
// convert converts s to the type of argument t and returns a value of that type.
func convert(s string, t interface{}) (interface{}, error) {
// Create pointer to value of the target type
v := reflect.New(reflect.TypeOf(t))
// Scan to the value by passing the pointer SScan
_, err := fmt.Sscan(s, v.Interface())
// Dereference the pointer and return the value.
return v.Elem().Interface(), err
}
可以这样称呼:
a := test()
a, err := convert("10", a)
fmt.Println(a, err)
您几乎不需要指向接口的指针。您很可能想要一个
接口{}
类型化的值,该值具有底层指针类型,例如*int
@ThunderCat问题是:将字符串转换为任何类型
。这种情况如何:?假设测试可以返回任何有效的基元类型。+我只在运行时知道它,所以我不能真正使用类型断言。