golang中的const常量和iota

golang中通过var定义变量,通过const定义常量。

常量只能是基本的简单值类型,常量一经定义其值不可修改(类比java中的final)。

const (
    maxint = int(^uint(0) >> 1)
    minint = -maxint - 1
)
const pi = 3.14
pi = 3.14159//编译错误,cannot assign to pi
iotaiota
const (
    a   = 1                  //1 (iota=0)
    b                        //1 (iota=1,同上一行,相当于写b=1)
    c   = b + iota           //3 (iota=2,b=1)
    d                        //4 (iota=3,同上一行,相当于写b+iota,b=1)
    e                        //5 (iota=4,同上一行,相当于写b+iota,b=1)
    f   = "last one but one" //  (iota=5)
    end = iota               //6 (iota=6)
)
fmt.println(a, reflect.typeof(a))
fmt.println(b, reflect.typeof(b))
fmt.println(c, reflect.typeof(c))
fmt.println(d, reflect.typeof(d))
fmt.println(e, reflect.typeof(e))
fmt.println(f, reflect.typeof(f))
fmt.println(end, reflect.typeof(end))
/* 
输出:
1 int
1 int
3 int
4 int
5 int
last one but one string
6 int
*/

golang定义常量

在所有的编程语言当中常量都代表一个固定的值,一旦常量被定义则无法修改。在golang中使用const关键字进行常量声明。

定义常量

golang定义常规类型的常量可以忽略类型。

const success = true
const fail = false

定义多个相同类型的常量

const (
const1 = 0
const2 = 1
const3 = 2
)

定义特定类型的常量

定义特定类型的常量需要根据实际情况来决定。

假如我们现在用常量来声明用户的三个基本状态(正常,禁止登录,删除),一般这种情况我们会首先声明一个用户状态的类型。

声明用户状态类型:

type userstatus int

定义用户状态常量:

const (
user_status_normal userstatus = iota
user_status_disabled_login
user_status_delete
)

完整示例:

package user
//status 用户类型.
type status int
const (
//status_normal 状态正常
status_normal status = iota
//status_disabled_login 禁止登录.
status_disabled_login
//status_delete 已删除.
status_delete
)

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。