Skip to content

testing: allow examples with any signature #79808

Description

@neild

This is an offshoot of #64993 (comment), and an alternative to #21111 and #64993.

Proposal:

We make go doc display any function named Example or ExampleXxx where Xxx does not start with a lowercase letter as an example. If the function has any input or output parameters, go doc displays just the function with no surrounding context.

The testing package will not run example functions with parameters. If an example function with parameters contains an // Output: comment, go test will produce an error.

For example, you could write any of the following examples, and they would show up in documentation in the expected places:

package examplepackage_test

func Example_returning_an_error() error {
  f, err := os.Open("testfile")
  if err != nil {
    return err
  }
  defer f.Close()
  examplepackage.F(f)
  return nil
}

func ExampleFunc_taking_a_t(t *testing.T) {
  if err := examplepackage.Func(t); err != nil {
    t.Fatal(err)
  }
}

func Example_in_and_out(a, b int) string {
  return examplepackage.AddReturningString(a, b)
}

None of the above would be run by the testing package. If you want to run them, you can add test functions which call the example functions:

func TestExample_returning_an_error(t *testing.T) {
  if err := Example_returning_an_error(); err != nil {
    t.Fatal(err)
  }
}

func TestExampleFunc_taking_a_t(t *testing.T) {
  ExampleFunc_taking_a_t(t)
}

func TestExample_in_and_out(t *testing.T) {
  for _, test := range []struct{
    a, b int
    want string
  }{
    {1, 2, "3"},
  }{
    if got, want := Example_in_and_out(test.a, test.b), test.want; got != want {
      t.Errorf("Example_in_and_out(%v, %v) = %q, want %q", test.a, test.b, got, want)
    }
  }
}

A question is how we would display these examples in go doc output. (See #21111 (comment) for current ways go doc presents examples.)

The simple option is to display the entire example func as a non-runnable example. (By "runnable", I mean runnable in your browser in the playground as for example https://pkg.go.dev/strings#example-Cut.)

A more complex possibility which I haven't thought through fully is that perhaps if an example has a paired test function (e.g., when there is an example func named ExampleFoo and a test func named TestExampleFoo) we could display the example func in a runnable playground panel where clicking "Run" executes the test.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    Status
    Accepted

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions