zoukankan      html  css  js  c++  java
  • Go语言常量

    常量是一个简单值的标识符,在程序运行时,不会被修改的量。

    常量中的数据类型只能是布尔型、数字型(整数型、浮点型和复数)和字符串型

    常量的定义格式:

    //const 常量名     类型      值
    const identifier [type] = value
    

    可以省略类型说明符[type],因为编译器可以根据变量值来推断其类型。

    • 显式类型定义: const b string = "itbsl"
    • 隐式类型定义: const b = "itbsl"

    无论是变量还是常量,不同类型的都不能显式的声明在一行:

    var a int, b float32 = 1, 2.4   //编译器不通过
    const c int, d float32 = 3, 4.4 //编译器不通过
    const c, d float32 = 3, 4 //编译通过(此时c和d都是float32类型)
    const c, d = 3, 4.4  //编译通过(此时c是int类型,d是float64类型)
    

    说明:我们可以通过reflect.Typeof(变量名)打印变量或常量的类型

    常量可以用len()、cap()、unsafe.Sizeof()常量计算表达式的值。常量表达式中,函数必须是内置函数,否则编译不通过,因为在编译期间自定义函数均属于未知,因此无法用于常量的赋值:

    package main
    
    import "unsafe"
    
    const (
        a = "cstxco"
        b = len(a)
        c = unsafe.Sizeof(a)
    )
    func main() {
        println(a, b, c)
    }
    

    iota

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

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

    const(
        a = iota
        b = iota
        c = iota
    )
    

    第一iota等于0,每当iota在新的一行被使用时,它的值都会自动加1;所以a=0,b=1,c=2,可以简写为如下形式:

    const(
    	a = iota
        b
        c
    )
    

    用法示例:

    package main
    
    import "fmt"
    
    func main() {
        const(
            a = iota     //0
            b            //1
            c            //2
            d = "itbsl" //独立值,iota += 1
            e            //itbsl iota += 1
            f = 200      //200  iota += 1
            g            //200 iota += 1
            h = iota     //7,恢复计数
            i            //8
        )
    
        fmt.Println(a, b, c, d, e, f, g, h, i)
    }
    

    输出结果为

    0 1 2 itbsl itbsl 200 200 7 8
    

    我们可以把iota理解为const里的行数

    const(
        a = iota
        b = iota
        c, d = iota, iota
    )
    fmt.Println(a, b, c, d)
    

    输出结果为

    0 1 2 2
    

    当我们定义常量时,如果多个常量的值相同,后面的常量可以直接不赋值,默认等同于上面已赋值的常量的值

    package main
    
    import "fmt"
    //当我们定义常量时,如果多个常量的值相同,后面的常量可以直接不赋值,默认等同于上面已赋值的常量的值
    const (
        a = "itbsl"
        c
        d
    )
    func main() {
        fmt.Println(a, c, d)
    }
    

    输出结果为

    itbsl itbsl itbsl
    
  • 相关阅读:
    Spring boot unable to determine jdbc url from datasouce
    Unable to create initial connections of pool. spring boot mysql
    spring boot MySQL Public Key Retrieval is not allowed
    spring boot no identifier specified for entity
    Establishing SSL connection without server's identity verification is not recommended
    eclipse unable to start within 45 seconds
    Oracle 数据库,远程访问 ora-12541:TNS:无监听程序
    macOS 下安装tomcat
    在macOS 上添加 JAVA_HOME 环境变量
    Maven2: Missing artifact but jars are in place
  • 原文地址:https://www.cnblogs.com/itbsl/p/9855140.html
Copyright © 2011-2022 走看看