package main import ( "fmt" "reflect" ) func main() { var foo int = 42 typ := reflect.TypeOf(foo) fmt.Println(typ) // "int" }
package main import ( "fmt" "reflect" ) func main() { var foo interface{} = "bar" typ := reflect.TypeOf(foo) if typ == reflect.TypeOf("") { fmt.Println("foo is a string") } else { fmt.Println("foo is not a string") } }
package main import ( "fmt" "reflect" ) type Person struct { Name string Age int Married bool } func main() { typ := reflect.TypeOf(Person{}) value := reflect.New(typ) value.Elem().FieldByName("Name").SetString("John") value.Elem().FieldByName("Age").SetInt(30) value.Elem().FieldByName("Married").SetBool(false) person := value.Interface().(Person) fmt.Println(person) // "{John 30 false}" }Package library: reflect In conclusion, the reflect package is a powerful tool for dynamically working with types in Go, and the Type Key provides a way to represent a type at runtime.