import ( "go/ast" "go/token" "golang.org/x/tools/go/types" ) // GetPackageName returns the name of the package contained in // the given abstract syntax tree. func GetPackageName(node *ast.File) string { return node.Name.Name } // Example usage: var fset *token.FileSet // initialized elsewhere node, err := parser.ParseFile(fset, "example.go", nil, parser.ParseComments) if err != nil { panic(err) } packageName := GetPackageName(node)
import ( "fmt" "go/ast" "go/types" ) // Function represents a Go function. type Function struct { Name string } // GetFunctions returns the list of functions contained in // the given abstract syntax tree. func GetFunctions(node *ast.File) []*Function { var functions []*Function for _, decl := range node.Decls { if fn, ok := decl.(*ast.FuncDecl); ok { functions = append(functions, &Function{Name: fn.Name.Name}) } } return functions } // Example usage: var node *ast.File // initialized elsewhere functions := GetFunctions(node) for _, fn := range functions { fmt.Println(fn.Name) }In both examples, the golang.org.x.tools.go.types Object is used indirectly through the use of the go/ast and go/types packages. These packages rely on the golang.org.x.tools.go.types Object to provide type information for a given Go program's syntax tree.