...
Source file
src/go/printer/example_test.go
1
2
3
4
5 package printer_test
6
7 import (
8 "bytes"
9 "fmt"
10 "go/ast"
11 "go/parser"
12 "go/printer"
13 "go/token"
14 "strings"
15 )
16
17 func parseFunc(filename, functionname string) (fun *ast.FuncDecl, fset *token.FileSet) {
18 fset = token.NewFileSet()
19 if file, err := parser.ParseFile(fset, filename, nil, 0); err == nil {
20 for _, d := range file.Decls {
21 if f, ok := d.(*ast.FuncDecl); ok && f.Name.Name == functionname {
22 fun = f
23 return
24 }
25 }
26 }
27 panic("function not found")
28 }
29
30 func printSelf() {
31
32
33
34 funcAST, fset := parseFunc("example_test.go", "printSelf")
35
36
37
38
39
40 var buf bytes.Buffer
41 printer.Fprint(&buf, fset, funcAST.Body)
42
43
44
45 s := buf.String()
46 s = s[1 : len(s)-1]
47 s = strings.TrimSpace(strings.ReplaceAll(s, "\n\t", "\n"))
48
49
50 fmt.Println(s)
51 }
52
53 func ExampleFprint() {
54 printSelf()
55
56
57
58
59
60
61
62
63
64
65
66
67 }
68
View as plain text