Skip to content

Commit 88b51d2

Browse files
SilverRainZmvdan
authored andcommitted
go/printer: make ExampleFprint correctly run as online example
function "ExampleFprint" will be rewritten to function "main" when displayed on the godoc pages, so the online example is failed to run: Output: panic: function not found goroutine 1 [running]: main.parseFunc({0x4f772e, 0xf}, {0x4f713f, 0xd}) /tmp/sandbox1264544227/prog.go:23 +0x13b main.main() /tmp/sandbox1264544227/prog.go:30 +0x45 See: https://pkg.go.dev/go/printer#example-Fprint Add printSelf function to prevent the function not found when running in godoc sandbox. Beside, deleting the dummy test function to make the example show the entire file, as we want to show the newly added printSelf function. Change-Id: Ia2b772937081b58a0fce9860838959c95f2d650c GitHub-Last-Rev: bac1189 GitHub-Pull-Request: #53141 Reviewed-on: https://go-review.googlesource.com/c/go/+/409314 TryBot-Result: Gopher Robot <[email protected]> Run-TryBot: Daniel Martí <[email protected]> Reviewed-by: Heschi Kreinick <[email protected]> Reviewed-by: Bryan Mills <[email protected]> Reviewed-by: Daniel Martí <[email protected]>
1 parent b35b4a3 commit 88b51d2

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

src/go/printer/example_test.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,8 @@ import (
1212
"go/printer"
1313
"go/token"
1414
"strings"
15-
"testing"
1615
)
1716

18-
// Dummy test function so that godoc does not use the entire file as example.
19-
func Test(*testing.T) {}
20-
2117
func parseFunc(filename, functionname string) (fun *ast.FuncDecl, fset *token.FileSet) {
2218
fset = token.NewFileSet()
2319
if file, err := parser.ParseFile(fset, filename, nil, 0); err == nil {
@@ -31,11 +27,11 @@ func parseFunc(filename, functionname string) (fun *ast.FuncDecl, fset *token.Fi
3127
panic("function not found")
3228
}
3329

34-
func ExampleFprint() {
30+
func printSelf() {
3531
// Parse source file and extract the AST without comments for
3632
// this function, with position information referring to the
3733
// file set fset.
38-
funcAST, fset := parseFunc("example_test.go", "ExampleFprint")
34+
funcAST, fset := parseFunc("example_test.go", "printSelf")
3935

4036
// Print the function body into buffer buf.
4137
// The file set is provided to the printer so that it knows
@@ -52,9 +48,13 @@ func ExampleFprint() {
5248

5349
// Print the cleaned-up body text to stdout.
5450
fmt.Println(s)
51+
}
52+
53+
func ExampleFprint() {
54+
printSelf()
5555

56-
// output:
57-
// funcAST, fset := parseFunc("example_test.go", "ExampleFprint")
56+
// Output:
57+
// funcAST, fset := parseFunc("example_test.go", "printSelf")
5858
//
5959
// var buf bytes.Buffer
6060
// printer.Fprint(&buf, fset, funcAST.Body)

0 commit comments

Comments
 (0)