44
27

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の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...と振ってくれる
  1. そのままだとPrintした時に、0とか1とか数字が出てしまうので、作成したtypeに対してString()メソッドを用意しておくと良い
  1. (おまけ) 大文字始まりのものは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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?