【问题标题】:How to use Sscan with interface如何在界面中使用 Sscan
【发布时间】: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

标签: string go interface


【解决方案1】:

以下是如何将字符串转换为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)

Run it on the Playground

【讨论】:

  • 这个案例怎么样:play.golang.org/p/MHfeDrNembl?假设 test 可以返回任何有效的原始类型。
  • + 我只在运行时知道,所以我不能真正使用类型断言。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-26
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 2016-01-09
  • 1970-01-01
相关资源
最近更新 更多