• 常量


    常量介绍:

    • 常量使用const 修改
    • 常量在定义的时候,必须初始化
    • 常量不能修改
    • 常量只能修饰bool、数值类型(int,float系列)、string 类型
    • 语法:const identifier [type] = value
    • 举例说明,看看下面的写法是否正确:

      const name = "tom" //ok
      const tax float64 = 0.8 //ok
      const a int //error
      const b = 9 / 3 //ok
      const b = num / 3 //error
      const c = getVal() //error

    常量没有默认值,声明的时候必须赋值。const tax int 是报错的,必须给值 const tax int = 0 才可以。

    常量使用注意事项:

    1)比较简洁的写法

    func main() {
      const (
        a = 1
        b = 2
      )
      fmt.Println(a,b)
    }

    2)还有一种专业的写法

    func main() {
      const (
        a = iota
        b
        c
      )
      fmt.Println(a,b,c) //0,1,2
    }

    表示给 a 赋值为0,b 在 a 的基础上+1, c 在 b 的基础上+1,这种写法就比较专业了。


    3)Golang中没有常量名必须字母大写的规范比如 TAX_RATE,比如:JAVA、PHP等等规定常量必须大写。

    4)仍然通过首字母的大小写来控制常量的访问范围。


    func main() {
      const (
        a = iota
        b = iota
        c, d = iota, iota //说明第二个iota并没有递增了。
      )
      fmt.Println(a,b,c,d) //0,1,2,2
    }

    上面的代码说明是一行就递增一次。

  • 相关阅读:
    python中的keys、values、items
    python中的del
    python中的reverse
    python中的remove
    python中的pop
    zookeeper for windows
    express
    js undefine,null 和NaN
    Think_php入口文件配置
    jquery 集合操作
  • 原文地址:https://www.cnblogs.com/green-frog-2019/p/11342660.html
Copyright © 2020-2023  润新知