Go 枚举 资料收集

方法1:直接手写代码:(参考:http://golang-basic.blogspot.com/2014/07/step-by-step-guide-to-declaring-enums.html)

package main

import "fmt"

// A Month specifies a month of the year (January = 1, ...).
type Month int

const (
	January Month = 1 + iota
	February
	March
	April
	May
	June
	July
	August
	September
	October
	November
	December
)

var months = [...]string{
	"January",
	"February",
	"March",
	"April",
	"May",
	"June",
	"July",
	"August",
	"September",
	"October",
	"November",
	"December",
}

// String returns the English name of the month ("January", "February", ...).
func (m Month) String() string {
	return months[m-1]
}

func main() {
	month := December
	if month == December {
		fmt.Println("Found a December")
	}
	// %!v(PANIC=runtime error: index out of range)
	month = month + Month(2)
	// fmt.Println(month)

	month = January + Month(2)
	fmt.Println(month)

	month++
	fmt.Println(month)

	day := 34
	month = Month(day % 31)
	fmt.Println(month)

	val := int(month) + 4
	fmt.Println(val)

	month = Month(val) + 1
	fmt.Println(month)
}

二、通过工具生成代码

声明enums.go

package main

type Month int

const (
	January Month = 1 + iota
	February
	March
	April
	May
	June
	July
	August
	September
	October
	November
	December
)

命令执行:

go get -v -u golang.org/x/tools/cmd/stringer (第一次使用需下载,×翻) 
stringer -type=Month

自动生成:(参考:http://godoc.org/golang.org/x/tools/cmd/stringer)

  创建:month_string.go

// generated by stringer -type=Month; DO NOT EDIT

package main

import "fmt"

const _Month_name = "JanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecember"

var _Month_index = [...]uint8{0, 7, 15, 20, 25, 28, 32, 36, 42, 51, 58, 66, 74}

func (i Month) String() string {
	i -= 1
	if i < 0 || i+1 >= Month(len(_Month_index)) {
		return fmt.Sprintf("Month(%d)", i+1)
	}
	return _Month_name[_Month_index[i]:_Month_index[i+1]]
}

使用:

package main

import (
	"fmt"
)

func main() {
	month := January
	fmt.Printf("%d\n", month)
	fmt.Println(January)
	month = month + Month(2)
	fmt.Printf("%d\n", month)
	fmt.Println(month)
}

感觉都有点小复杂 :)

转载于:https://my.oschina.net/u/1177938/blog/411398

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值