# 範例函式

本頁說明如何寫 `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`：

```go
package money

import (
	"fmt"
	"strconv"
)

type Wallet struct {
	cents int
}

func Format(cents int) string {
	return fmt.Sprintf("NT$%d.%02d", cents/100, cents%100)
}

func (w *Wallet) Deposit(cents int) {
	w.cents += cents
}

func (w *Wallet) String() string {
	return "wallet: " + strconv.Itoa(w.cents) + " cents"
}
```

測試檔 `example_test.go`：

```go
package money_test

import (
	"fmt"

	"example.com/money"
)

func ExampleFormat() {
	fmt.Println(money.Format(12345))
	fmt.Println(money.Format(5))
	// Output:
	// NT$123.45
	// NT$0.05
}
```

執行（`go.mod` 的 module 為 `example.com/money`）：

```bash
go test -v
```

輸出：

```text
=== RUN   ExampleFormat
--- PASS: ExampleFormat (0.00s)
PASS
ok  	example.com/money	0.229s
```

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

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

實際輸出和 `// Output:` 不一致時，`go test` 會把兩者並列（`got` 與 `want`），方便對照。

如果範例沒有 `// Output:` 註解，它只會被編譯（確保範例還能編譯），但不會被執行。適合輸出不固定的情況，例如會印出時間或啟動伺服器的範例。

測試檔 `example_test.go`（被測程式同上，故意把預期輸出寫錯）：

```go
package money_test

import (
	"fmt"

	"example.com/money"
)

func ExampleFormat() {
	fmt.Println(money.Format(12345))
	// Output:
	// NT$123.4
}

func ExampleFormat_noOutput() {
	fmt.Println(money.Format(100))
}
```

執行：

```bash
go test -v
```

輸出：

```text
=== RUN   ExampleFormat
--- FAIL: ExampleFormat (0.00s)
got:
NT$123.45
want:
NT$123.4
FAIL
exit status 1
FAIL	example.com/money	0.227s
```

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

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

有些輸出的順序本來就不固定，例如走訪[映射](/composite-maps)時的順序每次都可能不同。這時改寫 `// Unordered output:`，`go test` 只檢查「每一行都出現過」，不檢查先後。

測試檔 `example_test.go`（被測程式同上）：

```go
package money_test

import (
	"fmt"

	"example.com/money"
)

func ExampleFormat_map() {
	prices := map[string]int{"tea": 3500, "coffee": 6000, "cake": 8550}
	for name, cents := range prices {
		fmt.Println(name, money.Format(cents))
	}
	// Unordered output:
	// coffee NT$60.00
	// tea NT$35.00
	// cake NT$85.50
}
```

執行：

```bash
go test -v
```

輸出：

```text
=== RUN   ExampleFormat_map
--- PASS: ExampleFormat_map (0.00s)
PASS
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`（被測程式同上）：

```go
package money_test

import (
	"fmt"

	"example.com/money"
)

func Example() {
	var w money.Wallet
	w.Deposit(500)
	fmt.Println(money.Format(500))
	// Output: NT$5.00
}

func ExampleWallet() {
	w := &money.Wallet{}
	fmt.Println(w)
	// Output: wallet: 0 cents
}

func ExampleWallet_Deposit() {
	w := &money.Wallet{}
	w.Deposit(150)
	w.Deposit(50)
	fmt.Println(w)
	// Output: wallet: 200 cents
}

func ExampleWallet_Deposit_twice() {
	w := &money.Wallet{}
	w.Deposit(1)
	w.Deposit(1)
	fmt.Println(w)
	// Output: wallet: 2 cents
}
```

執行：

```bash
go test -v
```

輸出：

```text
=== RUN   Example
--- PASS: Example (0.00s)
=== RUN   ExampleWallet
--- PASS: ExampleWallet (0.00s)
=== RUN   ExampleWallet_Deposit
--- PASS: ExampleWallet_Deposit (0.00s)
=== RUN   ExampleWallet_Deposit_twice
--- PASS: ExampleWallet_Deposit_twice (0.00s)
PASS
ok  	example.com/money	0.231s
```

只有一行的輸出可以直接寫在 `// Output:` 後面。名稱對不上任何匯出識別字時，`go vet` 會提出警告；`go test` 執行前會自動跑這項檢查，所以測試也會失敗。例如把方法名稱拼成 `ExampleWallet_Depost`，`go test` 會輸出：

```text
# example.com/money_test
# [example.com/money_test]
./example_test.go:9:1: ExampleWallet_Depost refers to unknown field or method: Wallet.Depost
FAIL	example.com/money [build failed]
FAIL
```

### 出現在 go doc

範例會顯示在 HTML 版的文件中。在本機查看的方法是 `go doc -http`（Go 1.25 起）：它會啟動本機文件伺服器並用瀏覽器開啟目前套件的頁面。第一次執行時會下載文件伺服器所需的模組，需要網路。

純文字的 `go doc` 只顯示宣告與說明，不顯示範例。

使用上一節的 `money.go` 與 `example_test.go`，在套件目錄執行：

```bash
go doc -all
go doc -http
```

輸出：

```text
package money // import "example.com/money"


FUNCTIONS

func Format(cents int) string

TYPES

type Wallet struct {
	// Has unexported fields.
}

func (w *Wallet) Deposit(cents int)

func (w *Wallet) String() string
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` 不顯示範例

## 資料來源

- [gopl-zh/gopl-zh.github.com（《Go 語言聖經》中譯本，章節架構參考）](https://github.com/gopl-zh/gopl-zh.github.com)
- [The Go Programming Language Specification](https://go.dev/ref/spec)
- [Go 官方文件](https://go.dev/doc/)
- [Go 官方部落格](https://go.dev/blog/)
