Matthew
Matthew

Reputation: 453

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)

Upvotes: 4

Views: 6869

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109425

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.

Upvotes: 6

Related Questions