import ( "go/types" "fmt" ) func main() { var x int = 42 xType := types.TypeOf(x) // get the type of the variable fmt.Println(xType.String()) // prints 'int' }
import ( "go/types" ) type MyStruct struct { field1 string field2 int } func main() { var s MyStruct sType := types.TypeOf(s) field1Name := sType.Field(0).Name() // get the name of the first field }This code defines a struct type and uses types.TypeOf to get the type of a variable of that struct type. The Field method of the type object is used to get the field object for the first field, and then the Name method of the field object is used to get the name of that field.