Golang | 第一章 | 5.常量 &类型别名

0.像定义变量那样定义常量

const a=3.14

const(
    a=10
    b=23
)

1.枚举,现阶段Go没有真正的枚举,用iota模拟

※注意,代码放在同一个package下的另一个.go文件中,main.go(包含func main()的那个.go文件)可以直接调用而无需添加任何声明


type Month uint8

const  (
	jan Month=iota+1
	feb
	mar
	apr
)

当然,iota不光能+1,也能按位倍增

//enum.go中:
jan Month=1<<iota

//打印("%b"按二进制输出):
fmt.Printf("%b %b %b\n",jan,feb,mar)

out:
1
10
100
1000

2.枚举值转为字符串

枚举是用一个别名代表一个值,有时候想要那个别名(按字符串输出),需要重写String()方法

    枚举定义:

type Month int

const  (
	jan Month=1<<iota
	feb
)

//重写Month(int)类型的String()函数,Go的数据类型是有自己的函数的
func (c Month) String() string{
	switch c {
	case jan:
		return "jan"
	case feb:
		return "feb"
	}
	return "NULL"
}

    main()调用:

	fmt.Printf("%s %d\n",jan,feb)

out:
jan 2

类型别名

类型定义和类型别名的区别:

//类型定义
type int1 int

//类型别名
type int2=int

var(
	a int1
	b int2
)
fmt.Printf("%T %T \n",a,b)


out:
main.int1 int 

a的类型是main.int1.  表示main包下定义的int1类型

b就是int

posted @ 2019-10-19 11:39  心碎人俱乐部  阅读(13)  评论(0)    收藏  举报