LoginSignup
44
27

More than 5 years have passed since last update.

GoのEnumイディオム

Posted at
// RequestMethod defines http request method
type RequestMethod int

// Request methods
const (
    GET RequestMethod = iota
    POST
)

func (rm RequestMethod) String() string {
    switch rm {
    case GET:
        return "GET"
    case POST:
        return "POST"
    default:
        return "Unknown"
    }
}
  1. まずint型の別名としてtypeを設定する
  2. constのブロックの中でiotaを呼ぶと上から連番で0,1,2...と振ってくれる
  3. そのままだとPrintした時に、0とか1とか数字が出てしまうので、作成したtypeに対してString()メソッドを用意しておくと良い
  4. (おまけ) 大文字始まりのものはExportされるので、GoDoc用に上のような形でコメントを入れておく。そうしないと、golintでWarningが出る。

参考

44
27
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
44
27