简体   繁体   中英

golang scan in string or int

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM