菜单
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

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)
}
自己动手试一试 »

×

联系销售

如果您想将 W3Schools 服务用于教育机构、团队或企业,请发送电子邮件给我们
sales@w3schools.com

报告错误

如果您想报告错误,或想提出建议,请发送电子邮件给我们
help@w3schools.com

W3Schools 经过优化,旨在方便学习和培训。示例可能经过简化,以提高阅读和学习体验。教程、参考资料和示例会不断审查,以避免错误,但我们无法保证所有内容的完全正确性。使用 W3Schools 即表示您已阅读并接受我们的使用条款Cookie 和隐私政策

版权所有 1999-2024 Refsnes Data。保留所有权利。W3Schools 由 W3.CSS 提供支持