duan19780629 2019-01-21 18:59
浏览 36
已采纳

如何在界面上使用Sscan

I'm using to fmt.Sscan convert a string to any type, here is what I'm doing:

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)
}

This code is failing because Sscan doesn't accept interfaces as the second value: can't scan type: *interface {}. demo

What I find most weird is that the first print prints: int *interface {}, is it a int or an interface?

How can I assert a to the right type (it could be any primitive)? Is there a solution that doesn't include a giant switch statement?

Thank you.

  • 写回答

1条回答 默认 最新

  • duangai1368 2019-01-21 19:17
    关注

    Here's how to convert a string to a value of any type supported by the fmt package:

    // 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
    }
    

    Call it like this:

    a := test()
    a, err := convert("10", a)
    fmt.Println(a, err)
    

    Run it on the Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算