I have a simple function which takes a variable gets its type and processes it in to a switch but i get an error :
i is not a type
My code looks like this:
var whatAmI = func(i, interface{}) { // error is here
switch t := i.(type) {
case bool:
fmt.Println("I'm a bool!")
case int:
fmt.Println("I'm an int!")
default:
fmt.Println("Don't know type %T\n", t)
}
}
whatAmI(true)
whatAmI(1)
whatAmI("hey")
Am i misunderstanding something here?
Remove the comma from the function signature and it will work. Try it here.
package main
import (
"fmt"
)
func main() {
var whatAmI = func(i interface{}) { // error is here
switch t := i.(type) {
case bool:
fmt.Println("I'm a bool!")
case int:
fmt.Println("I'm an int!")
default:
fmt.Printf("Don't know type %T\n", t)
}
}
whatAmI(true)
whatAmI(1)
whatAmI("hey")
}
Also you were formatting the default case print statement incorrectly, so I changed it to match your expected behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With