6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go言語の自作パッケージに説明をつけてみる その1

Last updated at Posted at 2015-08-27

今回もドキュメントを見ながら勉強してみる。

Effective Go - Commentary

Go言語では、godocコマンドを使うことで各パッケージの説明を見ることができる。

$ godoc fmt
PACKAGE DOCUMENTATION

package fmt
    import "fmt"

    Package fmt implements formatted I/O with functions analogous to C's
    printf and scanf. The format 'verbs' are derived from C's but are
    simpler.


    Printing

    The verbs:

    General:

	%v	the value in a default format
		when printing structs, the plus flag (%+v) adds field names
	%#v	a Go-syntax representation of the value
	%T	a Go-syntax representation of the type of the value
...

で、自作パッケージの場合、何もしないと関数の定義など、ソースコードから自動で判別できる情報しか表示されないのだが(それが表示できるだけでも感動だけど)、そこに自分で書いた説明文を追加することができる。

上のfmtパッケージの例で言う以下の部分

Package fmt implements formatted I/O with functions analogous to C's
printf and scanf. The format 'verbs' are derived from C's but are
simpler.

やり方はとっても簡単。
パッケージ内のファイルのpackage宣言の直前にコメントを入れるだけ。

例えば前回作成したgithub.com/chooyan/mathパッケージに説明を加える場合、

$ cd $GOPATH/src/github.com/chooyan/math
$ vi sum.go
// Package math provides some simple calcuration functions.
// These are sample functions to practice golang.
package math

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

という感じで記述する。
※ 先頭のコメントとpackage宣言の間にスペースを入れないように注意!

で、確認する。

$ godoc github.com/chooyan/math
PACKAGE DOCUMENTATION

package math
    import "github.com/chooyan/math"

    Package math provides some simple calcuration functions. These are
    sample functions to practice golang.

FUNCTIONS

func Abs(i int) int

func Sum(a int, b int) int

出た出た。

ちなみにパッケージ内に複数の.goファイルがある場合は、どれか一つに説明が書いてあれば問題ない。

For multi-file packages, the package comment only needs to be present in one file, and any one will do.

他にも複数行にまたがって出す時は/* */で囲えば良いとか、特定の書き方しておけばgrepが便利だとかいろいろ書いてあるみたいだけど、それはまた別でまとめます。

6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?