Golang iota

本文通过示例代码介绍了Go语言中常量的使用方法,包括基本的整数常量、位移运算定义的单位转换常量以及带有初始化表达式的常量。此外,还展示了如何使用iota关键字来简化枚举类型的定义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Codes

package main

import "fmt"

type color byte

const (
    black color = iota
    red
    blue
)

func test(c color) {
    fmt.Println(c)
}

func main() {

    const (
        x = iota // 0
        y        // 1
        z        // 2
    )
    fmt.Printf("x=%v, y=%v, z=%v\n", x, y, z)

    const (
        _  = iota
        KB = 1 << (10 * iota) // 1 << (10 * 1)
        MB                    // 1 << (10 * 2)
        GB                    // 1 << (10 * 3)
    )
    fmt.Printf("KB=%v, MB=%v, GB=%v\n", KB, MB, GB)

    const (
        _, _   = iota, iota * 10 // 0, 0 * 10
        aa, bb                   // 1, 1 * 10
        cc, dd                   // 2, 2 * 10
    )
    fmt.Printf("aa=%v, bb=%v, cc=%v, dd=%v\n", aa, bb, cc, dd)

    const (
        a = iota // 0
        b        // 1
        c = 100  // 100
        d        // 100
        e = iota // 4
        f        // 5
    )
    fmt.Printf("a=%v, b=%v, c=%v, d=%v, e=%v, f=%v\n", a, b, c, d, e, f)

    const (
        g         = iota // 0
        h float32 = iota // 1
        i         = iota // 2
    )
    fmt.Printf("g: %T %v, f: %T %v, h: %T %v\n", g, g, h, h, i, i)

    test(black) // 0
    test(red)   // 1
    test(blue)  // 2
    test(100)   // 100 并未超出 color/byte 类型取值范围
    // xx := 2
    // test(xx)

}

Result

x=0, y=1, z=2
KB=1024, MB=1048576, GB=1073741824
aa=1, bb=10, cc=2, dd=20
a=0, b=1, c=100, d=100, e=4, f=5
g: int 0, f: float32 1, h: int 2
0
1
2
100

Reference

Go语言学习笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Digital2Slave

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值