範例函式

最後更新


本頁說明如何寫 ExampleXxx 範例函式:它既是會被 go test 驗證的測試,也是會顯示在套件文件中的使用範例。

什麼是範例函式


文件裡的範例程式最怕「過時」:API 改了,範例沒跟著改,讀者照抄就出錯。Go 的解法是把範例寫成程式碼放在 _test.go 中:
  • go test 會執行它,並比對印出的內容和 // Output: 註解是否一致
  • 文件工具(pkg.go.dev、go doc -http)會把它顯示在對應函式的說明下方

所以範例函式是「會自己檢查的文件」。只要測試通過,範例就保證能跑、輸出正確。
元素規則
函式名稱Example、ExampleF、ExampleT、ExampleT_M,可再加 _小寫後綴
簽名沒有參數、沒有回傳值
驗證函式結尾的 // Output: 註解;沒寫就只編譯、不執行

撰寫與驗證範例


ExampleXxx 與 // Output:


範例函式用 fmt.Println 等方式把結果印到標準輸出,最後寫一段 // Output: 註解列出預期輸出。go test 會擷取實際輸出,去掉前後空白後逐字比對。
範例通常放在外部測試套件(package 名稱加 _test,如 money_test),像真正的使用者一樣 import 套件、只用匯出的名稱。這樣文件中的範例就能直接複製使用。
被測程式 money.go:
  1. package money
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. type Wallet struct {
  7. cents int
  8. }
  9. func Format(cents int) string {
  10. return fmt.Sprintf("NT$%d.%02d", cents/100, cents%100)
  11. }
  12. func (w *Wallet) Deposit(cents int) {
  13. w.cents += cents
  14. }
  15. func (w *Wallet) String() string {
  16. return "wallet: " + strconv.Itoa(w.cents) + " cents"
  17. }

測試檔 example_test.go:
  1. package money_test
  2. import (
  3. "fmt"
  4. "example.com/money"
  5. )
  6. func ExampleFormat() {
  7. fmt.Println(money.Format(12345))
  8. fmt.Println(money.Format(5))
  9. // Output:
  10. // NT$123.45
  11. // NT$0.05
  12. }

執行(go.mod 的 module 為 example.com/money):
  1. go test -v

輸出:
  1. === RUN ExampleFormat
  2. --- PASS: ExampleFormat (0.00s)
  3. PASS
  4. ok example.com/money 0.229s

範例函式和 TestXxx 一起被執行。最後的耗時數字因機器而異。

輸出不符就失敗,沒寫 Output 就不執行


實際輸出和 // Output: 不一致時,go test 會把兩者並列(got 與 want),方便對照。
如果範例沒有 // Output: 註解,它只會被編譯(確保範例還能編譯),但不會被執行。適合輸出不固定的情況,例如會印出時間或啟動伺服器的範例。
測試檔 example_test.go(被測程式同上,故意把預期輸出寫錯):
  1. package money_test
  2. import (
  3. "fmt"
  4. "example.com/money"
  5. )
  6. func ExampleFormat() {
  7. fmt.Println(money.Format(12345))
  8. // Output:
  9. // NT$123.4
  10. }
  11. func ExampleFormat_noOutput() {
  12. fmt.Println(money.Format(100))
  13. }

執行:
  1. go test -v

輸出:
  1. === RUN ExampleFormat
  2. --- FAIL: ExampleFormat (0.00s)
  3. got:
  4. NT$123.45
  5. want:
  6. NT$123.4
  7. FAIL
  8. exit status 1
  9. FAIL example.com/money 0.227s

ExampleFormat_noOutput 沒有出現在結果中,因為它沒有 // Output:,只編譯不執行。

// Unordered output: 不在意順序的輸出


有些輸出的順序本來就不固定,例如走訪映射時的順序每次都可能不同。這時改寫 // Unordered output:,go test 只檢查「每一行都出現過」,不檢查先後。
測試檔 example_test.go(被測程式同上):
  1. package money_test
  2. import (
  3. "fmt"
  4. "example.com/money"
  5. )
  6. func ExampleFormat_map() {
  7. prices := map[string]int{"tea": 3500, "coffee": 6000, "cake": 8550}
  8. for name, cents := range prices {
  9. fmt.Println(name, money.Format(cents))
  10. }
  11. // Unordered output:
  12. // coffee NT$60.00
  13. // tea NT$35.00
  14. // cake NT$85.50
  15. }

執行:
  1. go test -v

輸出:
  1. === RUN ExampleFormat_map
  2. --- PASS: ExampleFormat_map (0.00s)
  3. PASS
  4. ok example.com/money 0.045s

雖然 map 的走訪順序不固定,三行內容都對得上,所以通過。
注意:如果能把資料排序後再印,就優先用一般的 // Output:,讀者看到的範例會更清楚;Unordered output 留給真的無法排序的情況。

命名規則:範例掛在哪個名稱下


範例函式的名稱決定它在文件中出現的位置:
函式名稱顯示在
Example整個套件的說明
ExampleF函式 F
ExampleT型別 T
ExampleT_M型別 T 的方法 M
ExampleT_M_suffix同上,用於同一個名稱的第二、三個範例;後綴必須以小寫字母開頭

測試檔 example_test.go(被測程式同上):
  1. package money_test
  2. import (
  3. "fmt"
  4. "example.com/money"
  5. )
  6. func Example() {
  7. var w money.Wallet
  8. w.Deposit(500)
  9. fmt.Println(money.Format(500))
  10. // Output: NT$5.00
  11. }
  12. func ExampleWallet() {
  13. w := &money.Wallet{}
  14. fmt.Println(w)
  15. // Output: wallet: 0 cents
  16. }
  17. func ExampleWallet_Deposit() {
  18. w := &money.Wallet{}
  19. w.Deposit(150)
  20. w.Deposit(50)
  21. fmt.Println(w)
  22. // Output: wallet: 200 cents
  23. }
  24. func ExampleWallet_Deposit_twice() {
  25. w := &money.Wallet{}
  26. w.Deposit(1)
  27. w.Deposit(1)
  28. fmt.Println(w)
  29. // Output: wallet: 2 cents
  30. }

執行:
  1. go test -v

輸出:
  1. === RUN Example
  2. --- PASS: Example (0.00s)
  3. === RUN ExampleWallet
  4. --- PASS: ExampleWallet (0.00s)
  5. === RUN ExampleWallet_Deposit
  6. --- PASS: ExampleWallet_Deposit (0.00s)
  7. === RUN ExampleWallet_Deposit_twice
  8. --- PASS: ExampleWallet_Deposit_twice (0.00s)
  9. PASS
  10. ok example.com/money 0.231s

只有一行的輸出可以直接寫在 // Output: 後面。名稱對不上任何匯出識別字時,go vet 會提出警告;go test 執行前會自動跑這項檢查,所以測試也會失敗。例如把方法名稱拼成 ExampleWallet_Depost,go test 會輸出:
  1. # example.com/money_test
  2. # [example.com/money_test]
  3. ./example_test.go:9:1: ExampleWallet_Depost refers to unknown field or method: Wallet.Depost
  4. FAIL example.com/money [build failed]
  5. FAIL

出現在 go doc


範例會顯示在 HTML 版的文件中。在本機查看的方法是 go doc -http(Go 1.25 起):它會啟動本機文件伺服器並用瀏覽器開啟目前套件的頁面。第一次執行時會下載文件伺服器所需的模組,需要網路。
純文字的 go doc 只顯示宣告與說明,不顯示範例。
使用上一節的 money.go 與 example_test.go,在套件目錄執行:
  1. go doc -all
  2. go doc -http

輸出:
  1. package money // import "example.com/money"
  2. FUNCTIONS
  3. func Format(cents int) string
  4. TYPES
  5. type Wallet struct {
  6. // Has unexported fields.
  7. }
  8. func (w *Wallet) Deposit(cents int)
  9. func (w *Wallet) String() string
  10. doc: Documentation server listening on addr http://localhost:62845

連接埠號碼每次不同。瀏覽器開啟的 http://localhost:<port>/example.com/money 頁面中:
範例函式出現位置
Example套件總覽(Overview)下的 Example
ExampleWallet型別 Wallet 下的 Example
ExampleWallet_Deposit方法 Deposit 下的 Example
ExampleWallet_Deposit_twice方法 Deposit 下的 Example (Twice)

每個範例都會顯示程式碼與 Output 區塊。發布到公開模組後,pkg.go.dev 也會用同樣方式呈現。按 Ctrl+C 結束伺服器。

重點整理


  • 範例函式寫在 _test.go,名稱為 Example、ExampleF、ExampleT、ExampleT_M,可加 _小寫後綴
  • // Output: 讓 go test 逐字比對輸出;沒寫就只編譯不執行
  • 輸出順序不固定時用 // Unordered output:
  • 範例放在外部測試套件(xxx_test),寫法和真正的使用者一樣
  • 範例會出現在 pkg.go.dev 與 go doc -http 的頁面;純文字 go doc 不顯示範例

資料來源