码迷,mamicode.com
首页 > 编程语言 > 详细

go语言的特殊变量 iota

时间:2018-09-18 19:12:32      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:结果   语言   关键字   多少   code   class   func   等于   +=   

iota,是go语言的特殊常量,可以认为是一个可以被编译器修改的常量。

在每一个const关键字出现时,被重置为0,然后在下一个const出现之前,每出现一次iota,其所代表的数字会自动增加1。

来看看代码:

const y = iota
const r = iota

func main() {
    fmt.Print("y的值为:")
    fmt.Println(y)
    fmt.Print("r的值为:")
    fmt.Println(r)   
}

每一个const关键字出现时,都被重置为0.所以输出为:

    y的值为:0
    r的值为:0

然后在下一个const出现之前,每出现一次iota,其所代表的数字会自动增加1。

const (
    q = iota
    w = iota
    e = iota
}
func main() {
    fmt.Print("q的值为:")
    fmt.Println(q)
    fmt.Print("w的值为:")
    fmt.Println(w)
    fmt.Print("e的值为:")
    fmt.Println(e)
}

输出:

    q的值为:0
    w的值为:1
    e的值为:2

其实个人认为iota最重要的部分是当做枚举值使用。

那么提出这样一个问题,如果要让e等于4 怎么办?

const (
    q = iota
    w = iota
    _
    _
    e = iota
}
func main() {
    fmt.Print("q的值为:")
    fmt.Println(q)
    fmt.Print("w的值为:")
    fmt.Println(w)
    fmt.Print("e的值为:")
    fmt.Println(e)
}
//输出
    q的值为:0
    w的值为:1
    e的值为:4

再看个特殊例子1,e的值是多少:

const (
    q = iota
    w = 100 ////即使w没有调用iota,但是同样会使iota += 1
    e = iota
}
func main() {
    fmt.Print("q的值为:")
    fmt.Println(q)
    fmt.Print("w的值为:")
    fmt.Println(w)
    fmt.Print("e的值为:")
    fmt.Println(e)
}

所以输出:

    q的值为:0
    w的值为:100
    e的值为:2

再看看个特殊例子2,w和e会延续上一级的q的使用,调用iota

const (
    q = iota
    w // w和e会延续上一级的q的使用,调用iota
    e //
    f = 100
    h = iota
}
func main() {
    fmt.Print("q的值为:")
    fmt.Println(q)
    fmt.Print("w的值为:")
    fmt.Println(w)
    fmt.Print("e的值为:")
    fmt.Println(e)
    fmt.Print("f的值为:")
    fmt.Println(f)
    fmt.Print("h的值为:")
    fmt.Println(h)
}

输出结果为:

    q的值为:0
    w的值为:1
    e的值为:2
    f的值为:100
    h的值为:4

再看看个特殊例子3,对于iota每新增一行 计数才加1 同一行 计数不加1。

const (
    q, w = iota + 1, iota + 3
    e, f
    h = iota
}
func main() {
    fmt.Print("q的值为:")
    fmt.Println(q)
    fmt.Print("w的值为:")
    fmt.Println(w)
    fmt.Print("e的值为:")
    fmt.Println(e)
    fmt.Print("f的值为:")
    fmt.Println(f)
    fmt.Print("h的值为:")
    fmt.Println(h)
}

输出的结果为,原因为   对于iota每新增一行 计数才加1 同一行 计数不加1。所以q为1,w为3.而e只去延续q,f只去延续w。

    q的值为:1
    w的值为:3
    e的值为:2
    f的值为:4
    h的值为:2

 

go语言的特殊变量 iota

标签:结果   语言   关键字   多少   code   class   func   等于   +=   

原文地址:https://www.cnblogs.com/nx520zj/p/9670262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!