01
概念
常量是一种表达式,常量的计算可以在编译时完成,如果有错误,在编译时就会报错,常量的值不可以修改。
02
声明常量
常量声明可以同时指定类型和值,如果没有显示指定类型,则类型根据右边的表达式推断。需要特别注意的是,声明常量不同于声明变量可以不赋值,声明常量必须赋值。
const name string = "golang" const PI = 3.14 func main() { fmt.Printf("name = %s type:%T\n", name, name) fmt.Printf("PI = %g type:%T\n", PI, PI) }
声明一组常量,每个常量类型可以不同。
const ( x = 1 y = "hello" z = true ) func main() { fmt.Printf("x = %d type:%T\n", x, x) fmt.Printf("y = %s type:%T\n", y, y) fmt.Printf("z = %t type:%T\n", z, z) }
声明一组常量,除了第一个常量之外,其他常量都可以省略表达式,其他常量会复用其前面一个常量的类型和表达式。
const ( a = 1 b c = 2 d ) func main() { fmt.Printf("a = %d type:%T\n", a, a) fmt.Printf("b = %d type:%T\n", b, b) fmt.Printf("c = %d type:%T\n", c, c) fmt.Printf("d = %d type:%T\n", d, d) }
03
常量生成器 iota
声明一组常量,可以使用常量生成器 iota,它可以不用逐个常量显示指定类型和赋值表达式,常量声明中,iota 从 0 开始取值,后续常量如果没有显示指定类型和赋值表达式,其值是其前面一个常量的值加 1。直到遇到赋值常量停止加 1,后续如果再遇到赋值 iota 的常量,则继续逐个加 1。
const ( Sunday int = iota Monday Tuesday Wednesday Thursday Friday Saturday ) const ( aa int = iota bb cc dd = 10 ee ff = iota gg hh ) func main() { fmt.Printf("Sunday = %d type:%T\n", Sunday, Sunday) fmt.Printf("Monday = %d type:%T\n", Monday, Monday) fmt.Printf("Tuesday = %d type:%T\n", Tuesday, Tuesday) fmt.Printf("Wednesday = %d type:%T\n", Wednesday, Wednesday) fmt.Printf("Thursday = %d type:%T\n", Thursday, Tuesday) fmt.Printf("Friday = %d type:%T\n", Friday, Friday) fmt.Printf("Saturday = %d type:%T\n", Saturday, Saturday) fmt.Printf("aa = %d type:%T\n", aa, aa) fmt.Printf("bb = %d type:%T\n", bb, bb) fmt.Printf("cc = %d type:%T\n", cc, cc) fmt.Printf("dd = %d type:%T\n", dd, dd) fmt.Printf("ee = %d type:%T\n", ee, ee) fmt.Printf("ff= %d type:%T\n", ff, ff) fmt.Printf("gg = %d type:%T\n", gg, gg) fmt.Printf("hh = %d type:%T\n", hh, hh) }
04
无类型常量
无类型常量,可以直接赋值给其他常量,显示指定类型的常量,赋值给其他常量时,会做强类型检查。
const username, age = "lucy", 17 const user = username func main() { fmt.Printf("username = %s, age = %d\n", username, age) fmt.Printf("user = %s\n", user) }
完整代码:
输出结果:
name = golang type:string PI = 3.14 type:float64 x = 1 type:int y = hello type:string z = true type:bool a = 1 type:int b = 1 type:int c = 2 type:int d = 2 type:int Sunday = 0 type:int Monday = 1 type:int Tuesday = 2 type:int Wednesday = 3 type:int Thursday = 4 type:int Friday = 5 type:int Saturday = 6 type:int aa = 0 type:int bb = 1 type:int cc = 2 type:int dd = 10 type:int ee = 10 type:int ff= 5 type:int gg = 6 type:int hh = 7 type:int username = lucy, age = 17 user = lucy