声明一个常量

常量声明为变量,但使用 const 关键字:

const Greeting string = "Hello World"
const Years int = 10
const Truth bool = true

与变量一样,以大写字母开头的名称将被导出( 公共 ),以小写字母开头的名称则不会。

// not exported
const alpha string = "Alpha"
// exported
const Beta string = "Beta"

除了无法更改值之外,常量可以像任何其他变量一样使用。这是一个例子:

package main

import (
    "fmt"
    "math"
)

const s string = "constant"

func main() {
    fmt.Println(s) // constant

    // A `const` statement can appear anywhere a `var` statement can.
    const n = 10
    fmt.Println(n)                           // 10
    fmt.Printf("n=%d is of type %T\n", n, n) // n=10 is of type int

    const m float64 = 4.3
    fmt.Println(m) // 4.3

    // An untyped constant takes the type needed by its context.
    // For example, here `math.Sin` expects a `float64`.
    const x = 10
    fmt.Println(math.Sin(x)) // -0.5440211108893699
}

操场