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