go const(常量)

常量介绍

示例

go 复制代码
package main

import (
	"fmt"
)

func main() {
	const name = "tom"
	fmt.Println(name)
	const tax float64 = 0.8
	fmt.Println(tax)
}
go 复制代码
go run const.go 
tom
0.8
go 复制代码
package main

import (
	"fmt"
)

func main() {
	const a int
	fmt.Println(a)
}
bash 复制代码
go run const.go 
# command-line-arguments
./const.go:8:8: missing init expr for a
go 复制代码
package main

import (
	"fmt"
)

func getVal() {
	fmt.Printf("测试")
}
func main() {
	const b = 9 / 3
	fmt.Println(b)
	//const c = getVal()
	//fmt.Println(c)
}
bash 复制代码
go run const.go 
3
go 复制代码
package main

import (
	"fmt"
)

func getVal() {
	fmt.Printf("测试")
}
func main() {
	//const b = 9 / 3
	//fmt.Println(b)
	const c = getVal()
	fmt.Println(c)
}
bash 复制代码
go run const.go 
# command-line-arguments
./const.go:13:12: getVal() (no value) used as value
go 复制代码
package main

import (
	"fmt"
)

func getVal() {
	fmt.Printf("测试")
}
func main() {
	//const b = 9 / 3
	//fmt.Println(b)
	//const c = getVal()
	//fmt.Println(c)
	num := 9
	const b = num / 3
	fmt.Println(b)
}
bash 复制代码
go run const.go 
# command-line-arguments
./const.go:16:12: num / 3 (value of type int) is not constant

常量比较简单的写法

go 复制代码
package main

import (
	"fmt"
)

func getVal() {
	fmt.Printf("测试")
}
func main() {
	const (
		a = 1
		b = 2
	)
	fmt.Println(a, b)
	const (
		c = iota
		d
		e
	)
	fmt.Println(c, d, e)
}
bash 复制代码
go run const.go 
1 2
0 1 2
相关推荐
m0_748708058 分钟前
C++中的观察者模式实战
开发语言·c++·算法
qq_5375626720 分钟前
跨语言调用C++接口
开发语言·c++·算法
wjs202431 分钟前
DOM CDATA
开发语言
Tingjct32 分钟前
【初阶数据结构-二叉树】
c语言·开发语言·数据结构·算法
猷咪1 小时前
C++基础
开发语言·c++
IT·小灰灰1 小时前
30行PHP,利用硅基流动API,网页客服瞬间上线
开发语言·人工智能·aigc·php
快点好好学习吧1 小时前
phpize 依赖 php-config 获取 PHP 信息的庖丁解牛
android·开发语言·php
秦老师Q1 小时前
php入门教程(超详细,一篇就够了!!!)
开发语言·mysql·php·db
烟锁池塘柳01 小时前
解决Google Scholar “We‘re sorry... but your computer or network may be sending automated queries.”的问题
开发语言
是誰萆微了承諾1 小时前
php 对接deepseek
android·开发语言·php