Getting reflect.Kind of a type based on a primitive type is an important skill in PHP programming. reflect.Kind is a property in the reflection class library provided by PHP, which can be used to determine the data type of a variable. By using reflect.Kind, we can easily obtain the type of the variable and perform corresponding operations and processing. For PHP developers, mastering this skill will help better understand and use the reflection mechanism, and improve the readability and flexibility of the code. In this article, PHP editor Baicao will introduce in detail how to obtain reflect.Kind based on primitive types, and share some practical examples and techniques to help readers better master this knowledge point.
I want to use reflect.kind as reflect.interface for a type that implements an interface, but its implementation is based on a primitive type:type id string
Another answer to this question might be how to get the reflect.type of whatever type returns reflect.interfaces when calling kind().
This is the complete example on the go playground:
type ID interface { myid() } type id string func (id) myid() {} func main() { id := ID(id("test")) fmt.Println(id) fmt.Println(reflect.TypeOf(id)) // How to get the kind to return "reflect.Interface" from the var "id"? fmt.Println(reflect.TypeOf(id).Kind()) }
reflect.typeof()
(andreflect.valueof()
) Requires ainterface {}
. Basically, whatever value you pass toreflect.typeof()
, if it's not already an interface value, it will be implicitly wrapped in aninterface{}
. If the value passed is already an interface value, the concrete value stored within it will be passed asinterface{}
.
To avoid this "repackaging", this is one of the rare cases where a pointer to an interface makes sense, in fact you can't avoid it here. You must pass a pointer to the interface value.
So if you pass a pointer to an interface, the pointer will be wrapped in aninterface{}
value. You can usetype.elem()
to get the type descriptor of the "pointer type": that is, the element type of the pointer type, which will be the type descriptor of the interface type you are looking for.
Example:
id := id(id("test")) fmt.println(id) t := reflect.typeof(&id).elem() fmt.println(t) fmt.println(t.kind())
What outputs (try it ongo playground):
test main.ID interface
View related questions:What is the difference between reflect.valueof() and value.elem() in go?
The above is the detailed content of Get reflect.Kind of a type based on a primitive type. For more information, please follow other related articles on the PHP Chinese website!