如何在界面上使用Sscan

user10312705:

我正在使用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 {}演示

我最奇怪的是第一张照片打印出来了:int *interface {},是int还是接口?

如何断言a正确的类型(可以是任何原始类型)?是否有不包含巨大的switch语句的解决方案?

谢谢。

松饼上衣:

将字符串转换为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)

在操场上运行

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在特定界面上使用cURL

如何在 Web 界面上使用 Owasp ZAP

如何在界面上的ui中显式排序任务?

打字稿:如何在界面上引用嵌套类型?

如何在新的Google Appscript界面上缩进代码?

如何在 Prometheus 用户界面上显示警报规则?

如何在Android中使用界面

如何在用户界面上显示(Primefaces)java List <Object>

在界面上使用省略的打字稿

如何在blazor页面上使用usermanager?

如何在多个页面上使用jQuery

如何使用bokeh库(Python + JavaScript)管理错误并将错误显示在用户界面上?

如何在NativeCall界面中正确使用CPointer和CStruct

如何在Kotlin的JS界面中使用可选参数调用

如何在Django管理界面中使用默认字体?

如何在界面中使用类型别名

会议室:如何在DAO界面中使用@Transaction

如何在Typescript界面中强制使用分号

如何在Google手机界面上的操作中显示列表卡时删除简单的响应

NetLogo 6.2版如何在界面上创建一个按钮来显示补丁变量的值?

如何使用VirtualDesktopManager界面?

Google Chrome在其用户界面上使用什么字体?

Collection <T>与List <T>在界面上应该使用什么?

如何在Django的所有页面上使用视图函数?

如何在github页面上使用jekyll设置集合?

如何在页面上的某些按钮上使用dropzone JS?

如何在点网的aspx页面上使用声明的变量

转到如何在HTML页面上使用JavaScript代码

如何在非HTML页面上使用Open Graph