golang学习之const和iota

golang中const和iota关键字

今天在看gjson时,发现了几句代码,感觉非常奇怪,如下:

// Type is Result type
type Type int
const (
	// Null is a null json value
	Null Type = iota
	// False is a json false boolean
	False
	// Number is json number
	Number
	// String is a json string
	String
	// True is a json true boolean
	True
	// JSON is a raw block of JSON
	JSON
)
func (t Type) String() string {
	switch t {
	default:
		return ""
	case Null:
		return "Null"
	case False:
		return "False"
	case Number:
		return "Number"
	case String:
		return "String"
	case True:
		return "True"
	case JSON:
		return "JSON"
	}
}

然后我自己尝试了一下,一直报错,然后往上搜索了一下相关东西,感觉有意思,所以记录下.

type a int
const sample int = 1
const(
	B a = sample
	C
	D
)
func (t a) String() string {
	switch t {
	default:
		return "1"
	case C:
		return "2"
	case D:
		return "3"
	}
}

golang中const定义,在const中()的常量必须是同一种类型。iota关键字在const关键中出现时其值为0,const每增加一行iota的值+1,所以gjson中False,Number,String,True的值默认是从0开始自增的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值