LoginSignup
1
0

More than 3 years have passed since last update.

Go言語のenumをもっと自由に

Last updated at Posted at 2019-08-29

前書き

Go言語はenum(列挙型)ような機能がありません
iotaで使用して実装してる場合は多いそうですが個人的にはmap使用してもいい気がします

実装例

package main

import "fmt"

const (
    StatusSuccess  = 200
    StatusErr      = 500
)

var statusText = map[int]string{
    StatusSuccess:  "success",
    StatusErr:      "error",
}

func StatusTexts(code int) string {
    str, ok := statusText[code]
    if ok {
        return str
    }
    return statusText[StatusErr]
}

func main() {
    fmt.Println(StatusTexts(1)) // error
}


最後に

あくまでも個人的気に入っているやり方、正解とは言えません

1
0
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
1
0