4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Golang には Test とは別に、Example という Prefix を持つ関数があります。
初めて見たとき、
Test と何が違うのか?
どんな場面で使うべきなのか?
が分からず、少し混乱しました。
調べてみると、両者は似ているようで目的が違うことが分かりました。

結論

Example の目的は「テスト」ではなく「ドキュメント」

Test: 正しさを検証するもの

Example: 使い方を説明するもの

Example は「この関数は、こう使うと、こういう結果になります」という実行可能なサンプルコードを提供するための仕組みです。

具体例

以下のようなadd関数を定義しました

main.go
package main

func add(a, b int) int {
	return a + b
}

この関数の使い方をドキュメントとして残したい場合、*_test.goファイルにExample関数を記述します。

main_test.go
package main

import "fmt"

func Example_add() {
	fmt.Println(add(2, 3))
	// Output: 5
}

ポイント

  1. *_test.goに書く

  2. ExmapleTestと同じように、*_test.goファイルに定義する
    出力結果をコメントで記述する

    // Output: 5
    
  3. go testで実行

  4. Exampleはgo test実行時に自動で実行され、

    • fmt.Println
    • // Output: コメント
      が一致しているかをGoがチェックします。
      ただし、これは「ロジックの正しさを保証」するのではないので注意してください。
  5. godocに表示される

まとめ

今回はExmapleについてまとめてみました。関数に入力値をいれたらどのような値が返ってくるかをドキュメントとして残したい場合は有用ですね。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?