本文摘自php中文网,作者(*-*)浩,侵删。

iota是golang语言的常量计数器,只能在常量的表达式中使用。
iota在const关键字出现时将被重置为0(const内部的第一行之前),const中每新增一行常量声明将使iota计数一次(iota可理解为const语句块中的行索引)。 (推荐学习:go)
使用iota能简化定义,在定义枚举时很有用。
在常量定义中,iota可以方便的迭代一个值从0以步长1递增,0,1,2,3,4,5…
本例以文件大小的格式2的10次方进位一次为依据,将KB为1左移10位,MB左移20位。。。
本文中的Sprintf(“%f”,x)并不会因为定义在String方法内而引起无穷循环bug,因为%f不会去尝试调用String()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | package main
import (
"fmt"
)
type ByteSize float64
const (
_ = iota
KB ByteSize = 1 << (10*iota)
MB
GB
TB
PB
EB
ZB
YB
)
func (b ByteSize) String() string{
switch {
case b >= YB:
return fmt.Sprintf("%.2fYB",b/YB)
case b >= ZB:
return fmt.Sprintf("%.2fZB",b/ZB)
case b >= EB:
return fmt.Sprintf("%.2fEB",b/EB)
case b >= PB:
return fmt.Sprintf("%.2fPB",b/PB)
case b >= TB:
return fmt.Sprintf("%.2fTB",b/TB)
case b >= GB:
return fmt.Sprintf("%.2fGB",b/GB)
case b >= MB:
return fmt.Sprintf("%.2fMB",b/MB)
case b >= KB:
return fmt.Sprintf("%.2fKB",b/KB)
}
return fmt.Sprintf("%.2fB",b)
}
func main() {
fmt.Println(ByteSize(1e10))
}
|
以上就是golang iota从几开始的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
golang判断是否存在不存在就创建文件
docker 概述
android one和android go有什么区别?
golang怎么判断套接字是否关闭
有趣的闭包
关于golang之排序使用
go语言操作数据库及其常规操作
一文搞懂如何实现 go 超时控制
golang pprof 性能分析工具
go函数用法实战
更多相关阅读请进入《golang》频道 >>
老貘
一个与时俱进的Go编程知识库。
转载请注明出处:木庄网络博客 » golang iota从几开始