mirror of
https://github.com/golang/go
synced 2024-09-05 16:04:50 +00:00
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: bac1189173
GitHub-Pull-Request: golang/go#53141
Reviewed-on: https://go-review.googlesource.com/c/go/+/409314
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
Reviewed-by: Heschi Kreinick <heschi@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
This commit is contained in:
parent
b35b4a31e1
commit
88b51d2e63
|
@ -12,12 +12,8 @@ import (
|
|||
"go/printer"
|
||||
"go/token"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Dummy test function so that godoc does not use the entire file as example.
|
||||
func Test(*testing.T) {}
|
||||
|
||||
func parseFunc(filename, functionname string) (fun *ast.FuncDecl, fset *token.FileSet) {
|
||||
fset = token.NewFileSet()
|
||||
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
|
|||
panic("function not found")
|
||||
}
|
||||
|
||||
func ExampleFprint() {
|
||||
func printSelf() {
|
||||
// Parse source file and extract the AST without comments for
|
||||
// this function, with position information referring to the
|
||||
// file set fset.
|
||||
funcAST, fset := parseFunc("example_test.go", "ExampleFprint")
|
||||
funcAST, fset := parseFunc("example_test.go", "printSelf")
|
||||
|
||||
// Print the function body into buffer buf.
|
||||
// The file set is provided to the printer so that it knows
|
||||
|
@ -52,9 +48,13 @@ func ExampleFprint() {
|
|||
|
||||
// Print the cleaned-up body text to stdout.
|
||||
fmt.Println(s)
|
||||
}
|
||||
|
||||
// output:
|
||||
// funcAST, fset := parseFunc("example_test.go", "ExampleFprint")
|
||||
func ExampleFprint() {
|
||||
printSelf()
|
||||
|
||||
// Output:
|
||||
// funcAST, fset := parseFunc("example_test.go", "printSelf")
|
||||
//
|
||||
// var buf bytes.Buffer
|
||||
// printer.Fprint(&buf, fset, funcAST.Body)
|
||||
|
|
Loading…
Reference in a new issue