66

Golang学习笔记-1.5 常量

 5 years ago
source link: https://studygolang.com/articles/13502?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文系第五篇Golang语言学习教程

在Go语言中,“常量”用于表示固定的值。

每种常量的潜在类型都是基础类型:bool、string、int、float32、float64

比如 5 -1 Go is interesting 3.1415

常量定义

一个常量声明语句定义了常量的名字,和变量的声明语法类似, 用关键字const定义常量

例:

package main
  
import "fmt"

func main(){
        const pai = 3.141592 //定义常量pai
        fmt.Println(pai)
}

以上程序输出结果:

3.141592

一个常量只能赋值一次,不能再赋值其他的值。否则报错 cannot assign to pai
例:

package main
  
import "fmt"

func main(){
        const pai = 3.141592 //定义常量pai
        pai = 2
        fmt.Println(pai)
}

所有常量的运算都可以在编译期完成,并且因为函数调用发生在运行时,所以不能将函数的返回值赋值给常量:

例:

package main
  
import (
        "fmt"
        "math"
)

func main(){
        var a = math.Sqrt(5) //允许将函数的返回值赋值给变量 a
        const b = math.Sqrt(5) //不允许将函数的返回值赋值给常量 b
        fmt.Println(a,b)
}

以上程序中,因为a是变量,所以可以将函数的返回值赋给a。

b是常量,它的值需要在编译的时候就确定。而函数的返回值只会在运行计算,所以以上程序会报错 const initializer math.Sqrt(5) is not a constant

常量类型

常量可以规定类型,也可以不规定类型。

如果不规定类型,那么它的类型就是不确定的。

例:

package main
  
import (
        "fmt"
)

func main(){
        const a,b = 3,4 //赋值常量 a,b  ,ab没有类型
        var c float64 = a //定义一个类型为float64的变量 c ,赋值a
        var d complex128 = b //定义一个类型为complex128的变量 d ,赋值b
        fmt.Printf("c's type is %T,d's type is %T\n",c,d)

}

以上程序输出结果:

c's type is float64,d's type is complex128

以上程序中,将 a,b 分别赋值给变量 c , d 并输出c,d的类型。

由此可以看出,常量的类型是根据表达式推断得出。

枚举类型

普通枚举类型

package main
  
import "fmt"

func main(){
        const (
                cpp = 0
                java = 1
                python = 2
                golang = 3
        )
        fmt.Println(cpp, java, python, golang)
}

以上程序定义了一个普通的const枚举类型

自增枚举类型

例1:

package main
  
import "fmt"

func main(){
        const (
                cpp = iota
                java
                python
                golang
                javascript
                perl
        )
        fmt.Println(cpp, java, python, golang, javascript, perl)
}

iota常量生成器:用于生成一组相似规则初始化的常量,但不用每行都写一遍初始化表达式。

以上程序中,在const声明语句中,在第一个常量声明所在的行,iota被置为0,然后在每一个有常量声明的行加一。

以上程序输出结果:

例2:

在复杂的常量表达式中使用iota

package main
  
import "fmt"

func main(){
        const (
                b = 1 <<(10* iota)
                KB
                MB
                GB
                TB
                PB
                EB
        )
        fmt.Println(b, KB, MB, GB, TB, PB, PB, EB)
}

左移运算符”<<”是双目运算符。左移n位就是乘以2的n次方。 其功能把”<<”左边的运算数的各二进位全部左移若干位,由”<<”右边的数指定移动的位数,高位丢弃,低位补0。

以上程序中,自增枚举每一行如下:

b = 1 * 2^(10 * 0)次方

KB = 1 * 2^(10 * 1) = 1 * 2^10 = 1024

MB = 1 * 2^(10 * 2) = 1 * 2^20 = 1048576

......

以上程序输出结果:

以上为学习Golang常量篇


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK