0
Help us understand the problem. What are the problem?

posted at

updated at

【備忘録】Golangでenum風に利用する

Golangでenum風に利用する。

Golangではenum型が提供されていないため、実装を工夫する事でenum風に利用する事ができます。

main.go
package main

import "fmt"

type Animal int

const (
	Unknown Animal = iota
	Dog
	Cat
	Horse
	Lion
	Tiger
	Rabbit
)

func (e Animal) Names() []string {
	return []string{
		"unknown",
		"犬",
		"猫",
		"馬",
		"ライオン",
		"トラ",
		"兎",
	}
}

func (e Animal) String() string {
	return e.Names()[e]
}

func main() {
	fmt.Printf("動物の名前は? %+v\n", Dog)
	fmt.Printf("動物の名前は? %+v\n", Cat)
	fmt.Printf("動物の名前は? %+v\n", Tiger)
}
実行結果
~/go/src/enum_go $ go run main.go
動物の名前は? 犬
動物の名前は? 猫
動物の名前は? トラ
package main

import "fmt"

type Animal string

const (
	Unknown Animal = "unknown"
	Dog = "犬"
	Cat = "猫"
	Horse = "馬"
	Lion = "ライオン"
	Tiger = "トラ"
	Rabbit = "兎"
)

func main() {
	var animal Animal
	animal = "犬"
	fmt.Println(animal)
}
実行結果
~/go/src/enum_go $ go run main.go
犬

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
0
Help us understand the problem. What are the problem?