1
0
mirror of https://github.com/golang/go synced 2024-11-20 02:54:39 -07:00

godoc: Allow examples for methods.

An example for a method M() of type T can be written as
func ExampleT_M() { ... }.
To differentiate between multiple examples for one function, type or
method a suffix with a lowercase start may be appended to the name
of the example function, e.g. ExampleFoo_basicUsage.

Fixes #2465.

R=golang-dev, adg, r, rsc, duperray.olivier, r
CC=golang-dev
https://golang.org/cl/5440100
This commit is contained in:
Volker Dobler 2011-12-16 10:01:54 +11:00 committed by Andrew Gerrand
parent 9834a25d33
commit cb7d6e37d8
2 changed files with 24 additions and 5 deletions

View File

@ -26,6 +26,8 @@ import (
"strings"
"text/template"
"time"
"unicode"
"unicode/utf8"
)
// ----------------------------------------------------------------------------
@ -482,14 +484,24 @@ func comment_textFunc(comment, indent, preIndent string) string {
return buf.String()
}
func startsWithUppercase(s string) bool {
r, _ := utf8.DecodeRuneInString(s)
return unicode.IsUpper(r)
}
func example_htmlFunc(funcName string, examples []*doc.Example, fset *token.FileSet) string {
var buf bytes.Buffer
for _, eg := range examples {
// accept Foo or Foo_.* for funcName == Foo
name := eg.Name
if i := strings.Index(name, "_"); i >= 0 {
name = name[:i]
// strip lowercase braz in Foo_braz or Foo_Bar_braz from name
// while keeping uppercase Braz in Foo_Braz
if i := strings.LastIndex(name, "_"); i != -1 {
if i < len(name)-1 && !startsWithUppercase(name[i+1:]) {
name = name[:i]
}
}
if name != funcName {
continue
}

View File

@ -35,8 +35,15 @@ os.Stdout and os.Stderr is compared against their doc comment.
fmt.Println("The output of this example function.")
}
Multiple example functions may be provided for a given name XXX if they are
discriminated by a distinct suffix starting with "_", such as ExampleXXX_2.
The following naming conventions are used to declare examples for a function F,
a type T and method M on type T:
func ExampleF() { ... } and func ExampleF_suffix() { ... }
func ExampleT() { ... } and func ExampleT_suffix() { ... }
func ExampleT_M() { ... } and func ExampleT_M_suffix() { ... }
Multiple example functions may be provided by appending a distinct suffix
to the name. The suffix must start with a lowercase letter.
Example functions without doc comments are compiled but not executed.
See the documentation of the testing package for more information.