douhuocuo9012 2016-06-14 13:15
浏览 114
已采纳

golang扫描为字符串或整数

I'm trying to write a function to input either a string or int something like the below, but can't find a way to do it... Not sure what I'm doing though, quite new to go....

func getUserInput(input interface{}) (int, error) {

    var err error

    switch t := input.(type) {
    default:
        fmt.Printf("unexpected type %T", t)
    case int:
        _, err = fmt.Scanf("%d", input)
    case string:
        _, err = fmt.Scanf("%s", input)
    }

    if err != nil {
        return 0, err
    }

    return 0, nil
}

and then use it something like (this doesn't work though!):

var firstName string
getUserInput(firstName)

var age int
getUserInput(age)
  • 写回答

1条回答 默认 最新

  • dongmeng1402 2016-06-14 13:31
    关注

    Your default case is first, so nothing else can ever match. Put that at the end. You can't scan into a value, you need a pointer, so change the type switch cases to their pointer equivalents.

    switch t := input.(type) {
    case *int:
        _, err = fmt.Scanf("%d", input)
    case *string:
        _, err = fmt.Scanf("%s", input)
    default:
        fmt.Printf("unexpected type %T", t)
    }
    

    You have to pass in a pointer to the interface argument, so use the use & operator there.

    var firstName string
    getUserInput(&firstName)
    
    var age int
    getUserInput(&age)
    
    • You lose the input, or only read part of it if you try to scan the wrong type. If you want to scan for multiple types, it's often better to read the token from stdin, and check that against the types you want. Not only do you then have the input for comparison, but you also have it to produce useful error messages.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题