4
4

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 で iota の最初を捨てるとき

Posted at

iota を使った定義

Go の iota は連番な定義をする時に便利です。
ただ、 0 から始まるので、 _ などで 0 を捨てる時はちょっと注意。

iota + 1 と _

例えば Status Code を const 定義するとき
SPDY は 1 から順番に始まるので以下のように定義したとします。

status.go
// RstStreamStatus represents the status that led to a RST_STREAM.
type RstStreamStatus uint32

const (
	ProtocolError      RstStreamStatus = 1
	InvalidStream                      = 2
	RefusedStream                      = 3
	UnsupportedVersion                 = 4
	// cont
)

これは iota を用いると以下のように書けます。

iota1.go
const (
	ProtocolError RstStreamStatus = iota + 1
	InvalidStream
	RefusedStream
	// cont
)

iota は 0 から始まるので、 +1 しているわけです。

「+1 とかなぁ。。」と思ったあなた。
_(アンダースコア) を使うと、最初の評価を捨てることができるので、
以下のようにも書けます。

iota2.go
const (
	_ RstStreamStatus = iota
	ProtocolError
	InvalidStream
	RefusedStream
	// cont
)

ああ、なんかそれっぽい。
と思ってた時期が僕にもありました。

godoc と _

しかし、これには重要な欠点があって。
_ だと go doc に表示されないんですよね。

最初を _ で捨てた場合。

_の場合

iota + 1 の場合。

iota+1の場合

ということで、 ドキュメントに残したい場合は iota+1 の方を使いましょう。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?