I'm really new to golang and I'm struggling with the basics. I wrote a piece of code like this:
package main
import (
"log"
"reflect"
)
if reflect.TypeOf([]string{"a"}).Elem() == reflect.String {
log.Println("success")
}
if reflect.TypeOf([]int{1}).Elem() == reflect.Int{
log.Println("success")
}
if reflect.TypeOf([]float64{1.00}).Elem() == reflect.Float64 {
log.Println("success")
}
When I run this code, I get the error
invalid operation: reflect.TypeOf([]string literal).Elem() == reflect.String (mismatched types reflect.Type and reflect.Kind)
I don't understand the documentation https://golang.org/pkg/reflect/ because I can't find examples of how to reference the different "types" or "kinds"
How should I be writing my if statements to do the comparisons I'm attempting?
reflect.Type
is an interface
with a method called Kind()
. As per document:
// Kind returns the specific kind of this type.
Kind() Kind
So you should write :
if reflect.TypeOf([]string{"a"}).Elem().Kind() == reflect.String {
log.Println("success")
}
To compare types, use:
if reflect.TypeOf([]string{"a"}).Elem() == reflect.TypeOf("") {
log.Println("success")
}
To compare kinds, use:
if reflect.TypeOf([]string{"a"}).Elem().Kind() == reflect.String {
log.Println("success")
}
If you want to test for a specific type, then compare types. If you want to determine what sort of type it is, then compare kinds.
This example might help:
type x string
The x
and string
types are both kinds of string. The kind comparison returns true for both:
fmt.Println(reflect.TypeOf(x("")).Kind() == reflect.String) // prints true
fmt.Println(reflect.TypeOf("").Kind() == reflect.String) // prints true
The x
and string
types are distinct:
fmt.Println(reflect.TypeOf(x("")) == reflect.TypeOf("")) // prints false
For simple type comparisons like what you're showing, you don't need reflection. You can use a type assertion instead:
stuff := []interface{}{"hello", 1, nil}
for _, obj := range stuff {
if _, ok := obj.(string); ok {
fmt.Printf("is a string\n")
} else if _, ok := obj.(int); ok {
fmt.Printf("is an int\n")
} else {
fmt.Printf("is something else\n")
}
}
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.