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.
Code
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Example Functions Assert Printed Output?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.