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
相关推荐
码叔义4 分钟前
Jsonpath 使用说明
android·开发语言·javascript
行十万里人生18 分钟前
Qt 对象树详解:从原理到运用
开发语言·数据库·qt·华为od·华为·华为云·harmonyos
原来是猿23 分钟前
蓝桥备赛(四)- 数组(下)
开发语言·数据结构·c++·算法
心流时间26 分钟前
[Java基础] JVM常量池介绍(BeanUtils.copyProperties(source, target)中的属性值引用的是同一个对象吗)
java·开发语言·jvm
网络安全Ash29 分钟前
Python网络安全脚本
开发语言·python·web安全
.猫的树1 小时前
Java集合List快速实现重复判断的10种方法深度解析
java·开发语言·list·集合
刀客1231 小时前
C++ STL(三)list
开发语言·c++
朔北之忘 Clancy2 小时前
2022 年 12 月青少年软编等考 C 语言五级真题解析
c语言·开发语言·c++·学习·算法·青少年编程·题解
折枝寄北2 小时前
(21)从strerror到strtok:解码C语言字符函数的“生存指南2”
c语言·开发语言
m0_748236582 小时前
PHP进阶-在Ubuntu上搭建LAMP环境教程
开发语言·ubuntu·php