Example Functions Assert Printed Output

Example functions run under go test with their // Output: comment compared verbatim, keeping documentation snippets honest as the code evolves.

GoData Integrity

Code

gosnippet
31 lines
package main

import (
	"fmt"
	"strings"
)

// initials 取每个单词的首字母并大写
func initials(s string) string {
	words := strings.Fields(s)
	var b strings.Builder
	for _, w := range words {
		b.WriteByte(strings.ToUpper(w[:1])[0])
	}
	return b.String()
}

func main() {
	fmt.Println(initials("ada byron lovelace"))
	fmt.Println(initials("grace hopper"))
}

// Example_initials 由 go test 运行:
// 注释里 // Output: 之后的行与实际输出逐字比对,不一致即测试失败
func Example_initials() {
	fmt.Println(initials("ada byron lovelace"))
	fmt.Println(initials("grace hopper"))
	// Output:
	// ABL
	// GH
}

What happens when it runs

Under the hood: the functions initials, main and Example_initials.

Repetition is confined to for _, w := range words — the rest of the file is straight-line.

Points of care

  • Built-in APIs only — there is no supply chain to vet.

Using it

The central signature reads: func Example_initials()

The demo flow inside main is initials and Example_initials — run the file to see it end to end.

Key statements

func initials(s string) string {
	words := strings.Fields(s)
	var b strings.Builder
	for _, w := range words {
		b.WriteByte(strings.ToUpper(w[:1])[0])
	}
	return b.String()
}
func Example_initials() {
	fmt.Println(initials("ada byron lovelace"))
	fmt.Println(initials("grace hopper"))
	// Output:
	// ABL
	// GH
}
func main() {
	fmt.Println(initials("ada byron lovelace"))
	fmt.Println(initials("grace hopper"))
}

Interactive Tools for This Topic

FAQ

How do you run Example Functions Assert Printed Output?
Execute it straight away — the program needs nothing beyond the runtime.