import ( "go/types" "golang.org/x/tools/go/packages" ) func main() { cfg := &packages.Config{Mode: packages.LoadTypes} pkgs, _ := packages.Load(cfg, "fmt") fmtPkg := pkgs[0].Types // types.Package fmt.Printf("Package name: %s\n", fmtPkg.Name()) for _, imp := range fmtPkg.Imports() { fmt.Printf("Imported package: %s\n", imp.Path()) } }
import ( "go/types" ) type Person struct { Name string `json:"name"` Age int `json:"age"` Email string `json:"email,omitempty"` } func main() { p := Person{} pType := types.NewPointer(types.NewNamed(nil, nil, types.NewStruct( []*types.Var{ types.NewVar(0, nil, "Name", types.NewNamed(nil, nil, types.Typ[types.String])), types.NewVar(0, nil, "Age", types.NewNamed(nil, nil, types.Typ[types.Int])), types.NewVar(0, nil, "Email", types.NewNamed(nil, nil, types.Typ[types.String])), }, []*types.Func{}, []*types.Named{}, ), nil)) pVal := types.NewPointer(types.NewStruct( []*types.Var{ types.NewField(0, nil, "Name", types.NewNamed(nil, nil, types.Typ[types.String]), false), types.NewField(0, nil, "Age", types.NewNamed(nil, nil, types.Typ[types.Int]), false), types.NewField(0, nil, "Email", types.NewNamed(nil, nil, types.Typ[types.String]), true), }, []*types.Func{}, []*types.Named{}, )) for i := 0; i < pType.NumFields(); i++ { field := pType.Field(i) val := pVal.Field(i) fmt.Printf("%s (%s) - tag: %s\n", field.Name(), field.Type(), val.Tag().Get("json")) } }This code defines a Person struct and uses the types package to create a types.Struct value representing the same struct. It then iterates over the struct's fields and prints their names, types, and JSON tags.