In Go, reflection allows you to inspect and manipulate types at runtime. The reflect package provides powerful tools to obtain detailed type information. This can be useful for various purposes, such as debugging, serialization, and dynamic type handling.
reflect package provides Type and Value types. Type represents the type of a variable, and Value represents the value of a variable.reflect.Struct, reflect.Int, reflect.Slice, etc.Let's create an example where we define a struct and use reflection to obtain and display detailed type information.
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
}
func (p Person) Greet() {
fmt.Printf("Hello, my name is %s.\\\\n", p.Name)
}
func (p Person) GetAge() int {
return p.Age
}
package main
func printTypeInfo(i interface{}) {
t := reflect.TypeOf(i)
v := reflect.ValueOf(i)
fmt.Printf("Type: %s\\\\n", t)
fmt.Printf("Kind: %s\\\\n", t.Kind())
if t.Kind() == reflect.Struct {
fmt.Println("Fields:")
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fieldValue := v.Field(i)
fmt.Printf(" %s (%s): %v\\\\n", field.Name, field.Type, fieldValue.Interface())
}
fmt.Println("Methods:")
for i := 0; i < t.NumMethod(); i++ {
method := t.Method(i)
fmt.Printf(" %s (%s)\\\\n", method.Name, method.Type)
}
}
}
func main() {
person := Person{Name: "Alice", Age: 30}
printTypeInfo(person)
}
Person with fields Name and Age, and methods Greet and GetAge.reflect.TypeOf(i) to get the type of the input parameter.reflect.ValueOf(i) to get the value of the input parameter.t.String() and t.Kind().reflect.Struct, we:
t.NumField() and t.Field(i).v.Field(i).Interface().t.NumMethod() and t.Method(i).Person and pass it to printTypeInfo to display detailed type information.The output of the above code will be:
Type: main.Person
Kind: struct
Fields:
Name (string): Alice
Age (int): 30
Methods:
GetAge (func(main.Person) int)
Greet (func(main.Person))