为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用带界面的 Sscan

如何使用带界面的 Sscan

Go
慕雪6442864 2023-06-01 17:56:47
我正在使用将fmt.Sscan字符串转换为任何类型,这就是我正在做的事情:package mainimport (    "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 {}。演示我觉得最奇怪的是第一个 print 打印:int *interface {}, is it a int or an interface?我如何断言a正确的类型(它可以是任何原始类型)?有没有不包含巨型 switch 语句的解决方案?谢谢。
查看完整描述

1 回答

?
慕斯709654

TA贡献1840条经验 获得超5个赞

以下是将字符串转换为包支持的任何类型的值的方法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)

在操场上运行


查看完整回答
反对 回复 2023-06-01
  • 1 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信