Reputation: 453
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
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)
Upvotes: 6