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でenumっぽいので表示名を作る

Posted at

いつも忘れるのでメモ

time.Monthとかtime.Weekdayあたりが参考になる。
Goにはenum的なものがないので代わりに定数とiotaを使う。
(こういう時なんていう表現なのかわらないのだけど)この時int型をwrapした
enum用の型を作成してそいつにメソッドつける感じで対応する。

enum.go

type EnumType int

const (
  One EnumType = iota //初期値を0以外にする場合は iota+1とかで調整
  Tow
  Three
)

//EnumType の文字列表現
var enumTypes = [...]string{
  "一",
  "二",
  "三",
}

//Enum→string
func (e EnumType) String() string { return enumTypes[e]}

//string→Enum こっちは微妙
func ParseEnumType(name string) EnumType {
	for i, display := range enumTypes {
		if name == display {
			return EnumType(i)
		}
	}
	return One  
}

//int → Enum は EnumType(int)とかでやるはず
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?