导航
×
   ❮   
HTML CSS JavaScript PHP Go ECMS

Go 常量


Go 常量

如果一个变量应该有一个固定且不可更改的值,您可以使用 const 关键字。

The const keyword declares the variable as "constant", which means that it is unchangeable and read-only.

语法

const CONSTNAME type = value

注意: 常量的必须在声明时赋值。


声明常量

Here is an example of declaring a constant in Go

实例

package main
import ("fmt")

const PI = 3.14

func main() {
  fmt.Println(PI)
}
亲自试一试 »

常量规则

  • Constant names follow the same naming rules as variables
  • 常量名称通常使用大写字母(以便于识别和区分变量)
  • 常量可以在函数内部或外部声明

常量类型

There are two types of constants

  • Typed constants
  • Untyped constants

已声明类型的常量

Typed constants are declared with a defined type

实例

package main
import ("fmt")

const A int = 1

func main() {
  fmt.Println(A)
}
亲自试一试 »

未声明类型的常量

Untyped constants are declared without a type

实例

package main
import ("fmt")

const A = 1

func main() {
  fmt.Println(A)
}
亲自试一试 »

注意: In this case, the type of the constant is inferred from the value (means the compiler decides the type of the constant, based on the value).


常量:不可更改,只读

When a constant is declared, it is not possible to change the value later

实例

package main
import ("fmt")

func main() {
  const A = 1
  A = 2
  fmt.Println(A)
}

结果

./prog.go:8:7: cannot assign to A
亲自试一试 »

多个常量声明

Multiple constants can be grouped together into a block for readability

实例

package main
import ("fmt")

const (
  A int = 1
  B = 3.14
  C = "Hi!"
)

func main() {
  fmt.Println(A)
  fmt.Println(B)
  fmt.Println(C)
}
亲自试一试 »

freew3c.com 中文网是独立运营的中文开发者学习平台,与 freew3c.com 无关联。提供的内容仅用于学习和测试,不保证内容的正确性。


Copyright @2020-2026 京ICP备888888号-8