package main import ( "fmt" "go/ast" "go/parser" "go/token" ) func main() { // Parse Go source code fset := token.NewFileSet() astFile, err := parser.ParseFile(fset, "main.go", nil, parser.ParseComments) if err != nil { fmt.Println(err) return } // Print the AST tree ast.Print(fset, astFile) }
package main import ( "fmt" "go/ast" "go/parser" "go/token" ) func main() { // Parse Go source code fset := token.NewFileSet() astFile, err := parser.ParseFile(fset, "main.go", nil, parser.ParseComments) if err != nil { fmt.Println(err) return } // Find all function declarations var funcDecls []*ast.FuncDecl for _, decl := range astFile.Decls { if funcDecl, ok := decl.(*ast.FuncDecl); ok { funcDecls = append(funcDecls, funcDecl) } } // Print function names and their start and end positions for _, decl := range funcDecls { fmt.Printf("%s: [%v, %v]\n", decl.Name.Name, decl.Pos(), decl.End()) } }This code parses the `main.go` file, extracts all function declarations using the `ast.FuncDecl` type, and prints their names along with their start and end positions. Package library: `go/ast`