I'm quite confused about the .(type) syntax for interface variables. Is it possible to use it like this:
var a,b interface{}
// some code
if first.(type) == second.(type) {
}
or is reflect.TypeOf() the only option to check if the underlying types of a and b are the same type? What comparison am I making in the code above?
func isType(a, b interface{}) bool {
return fmt.Sprintf("%T", a) == fmt.Sprintf("%T", b)
}
The "%T"
fmt option uses reflection under the hood, which would make the above statement practically that same as:
func isType(a, b interface{}) bool {
return reflect.TypeOf(a) == reflect.TypeOf(b)
}
Either one would work, and won't cause a panic trying to utilize any kind of type assertion like some of the other suggestions.
You'd need to specify the type. That syntax is used to make type assertions about interfaces, not about checking the specific type.
You'll have to use reflect.TypeOf
for that.
You can view this answer for a proper use of type assertions.
someInterface.(type)
is only used in type switches. In fact if you tried to run that you'd see that in the error message.
func main() {
var a, b interface{}
a = 1
b = 1
fmt.Println(a.(type) == b.(type))
}
prog.go:10: use of .(type) outside type switch
What you could do instead is a.(int) == b.(int)
, which is really no different from int(a) == int(b)
func main() {
var a, b interface{}
a = 1
b = 1
fmt.Println(a.(int) == b.(int))
}
true
Please try this:
for key, value := range data {
switch v := value.(type) {
case string:
fmt.Println(key, value, "(string)")
case float64:
fmt.Println(key, value, "(float64)")
case []interface{}:
fmt.Println(key, value, "(interface)")
}
}
... and you can use for all types in any interface...
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