Accepted proposal: Go examples with any signature

Go’s proposal to allow examples with any signature was accepted on July 8. Today, an example must look like func ExampleXxx(). go/doc skips the function as soon as it sees a parameter or result. The example doesn’t appear in go doc or on pkg.go.dev.

The restriction comes from the two jobs an example can do: appear in documentation and run as a test. The test behavior starts when the function has a trailing // Output: comment.

The generated test harness can call ExampleXxx() because it needs no arguments and returns nothing. go test captures the function’s stdout, then compares that text with the comment. Without an output comment, the example is compiled but isn’t executed.

The zero-argument signature gets in the way when an API expects a value supplied by the caller. For example, testing/synctest.Test takes a *testing.T as its first argument. An example of a normal call needs the same parameter:

func ExampleTest(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        start := time.Now()
        time.Sleep(time.Hour)
        if elapsed := time.Since(start); elapsed != time.Hour {
            t.Fatalf("time advanced by %v", elapsed)
        }
    })
}

Current tooling leaves that function out of the generated examples. The accepted rules change that. go doc will put it alongside synctest.Test and show the complete declaration, including the signature and any doc comment attached to the function.

The new rule also covers examples that return an error. They can use a regular Go signature instead of calling log.Fatal or wrapping the body in an anonymous function:

func ExampleCreateTemp() error {
    f, err := os.CreateTemp("", "example")
    if err != nil {
        return err
    }
    defer os.Remove(f.Name())

    if _, err := f.WriteString("content"); err != nil {
        f.Close()
        return err
    }
    return f.Close()
}

Examples with parameters or results are documentation only. They don’t get a playground Run button, and go test doesn’t call…

添加评论
点赞收藏
点踩分享查看原文
评论
?
参与讨论