- 常量
常量
const (PI = 3.14World = '世界')println(PI)println(World)
常量通过const关键字定义,只能在模块级别定义常量,不能在函数内部定义常量。
常量名必须大写字母开头。这样有助于区别常量和变量。
常量值永远不会被改变。
V语言的常量支持多种类型,甚至是复杂类型的值:
struct Color {r intg intb int}fn (c Color) str() string { return '{$c.r, $c.g, $c.b}' }fn rgb(r, g, b int) Color { return Color{r: r, g: g, b: b} }const (Numbers = [1, 2, 3]Red = Color{r: 255, g: 0, b: 0}Blue = rgb(0, 0, 255))println(Numbers)println(Red)println(Blue)
因为不支持全局的变量,所以支持全局的复杂类型的常量就变得很有必要。
