Weekday:以int为底层类型,眼熟【自定义类型 + iota】 的枚举写法 type 关键字,用于定义自定义类型或给已有类型取别名
type Weekday int自定义类型,这里需注意:Weekday ≠ int 虽然存储的数据类型相同,但是Weekday与int之间的赋值必须显示转换。
const()可以批量定义常量
const ( Sunday Weekday = iota Mondat Tuesday Wednesday Thursday Friday Saturday )iota 是常量生成器,从0开始,每次累加。首个常量使用之后其余自动累加。同行内iota值相同
这里需要注意的是 Atoi和Itoa,他们相似但是作用不同,Atoi和Itoa是strconv里面的两个方法,用于把字符串和整形之间互相转化。Atoi:str-》int,Itoa:int-》str
func (d Weekday) String() string { // 值接收者方法: 等价于 func String(d Weekday) string names := [...]string{ // [...] 让编译器按元素个数推导数组长度(此处为 7) "周日", // 下标 0 "周一", // 下标 1 "周二", // 下标 2 "周三", // 下标 3 "周四", // 下标 4 "周五", // 下标 5 "周六", // 下标 6 } // 数组字面量结束 if d < Sunday || d > Saturday { // 边界检查, 避免下标越界导致 panic return fmt.Sprintf("Weekday(%d)", int(d)) // %d 需要整型实参, 所以显式转换 } // if 结束 return names[d] // 整数类型可直接作数组下标; 返回元素的副本 } // 方法结束该函数属于Weekday类型的专属函数,任何Weekday类型的常量以及变量都可以调用该函数
函数的具体作用就是根据变量或常量的值来进行判断,输出日期或者其他信息
使用场景:订单状态,待支付、已支付、已发货、已完成、已取消
由于1.26版本的go依旧没有枚举,所以使用上面的自定类型+iota来进行。接下来是订单状态的完整示例
type OrderStatus int const ( OrderPending OrderStatus = iota OrderPaid OrderShipped OrderCompleted OrderCancelled ) func (o OrderStatus) String() string { Status := [...]string{"Pending", "Paid", "Shipped", "Completed", "Cancelled"} if o < OrderPending || o > OrderCompleted { return "数据越界" } return Status[o] } func main() { order1 := OrderPending fmt.Println(order1.String()) }第二个例子,权限控制的例子
type UserPermission int const ( CanRead UserPermission = 1 << iota CanWrite CanExecute ) func (u UserPermission) OutputPermission() { permissions := [...]struct { permission UserPermission name string }{ {CanRead, "CanRead"}, {CanWrite, "CanWrite"}, {CanExecute, "CanExecute"}, } for _, p := range permissions { if p.permission&u == p.permission { fmt.Println("Can ", p.name) } else { fmt.Println("Can not ", p.name) } } } func main() { user1 := CanRead | CanWrite user1.OutputPermission() }位运算 与或非 & | ^ 左移<< 右移>>
| 左值 | 右值 | 结果 | |
| & | 1 | 0 | 0 |
| 0 | 1 | 0 | |
| 0 | 0 | 0 | |
| 1 | 1 | 1 | |
| | | 1 | 0 | 1 |
| 0 | 1 | 1 | |
| 0 | 0 | 0 | |
| 1 | 1 | 1 | |
| ^ | 1 | 0 | |
| 0 | 1 | ||
| << | 公式:a<<n a左移n位,a*2^n | ||
| >> | 公式:a>>n a右移n位a/2^n | 右移自动去掉小数位 |