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
相关推荐
朝朝辞暮i5 小时前
C++ 第 23 课:class —— 开始真正进入面向对象
开发语言·c++·算法
小师兄吃牛肉6 小时前
C语言篇:宏
c语言·开发语言
郑同学的笔记6 小时前
【c++随笔28】strcmp 和 memcmp对比
开发语言·c++
言乐67 小时前
Python根据无法识别搜索词找出可能输入内容模型
开发语言·python·django·virtualenv·pygame
weixin_307779137 小时前
有限产能智能排产与动态重排智能体:从需求解构到技术实现
开发语言·人工智能·算法·架构
kakakahahahaha7 小时前
Windows C盘临时文件清理:%temp%、Windows Temp、Prefetch、Windows.old与hiberfil.sys处理指南
c语言·开发语言·windows
朝朝辞暮i7 小时前
C++ 第 27 课:智能指针 shared_ptr
开发语言·c++·算法
朝朝辞暮i8 小时前
C++ 第 29 课:回调函数 Callback
开发语言·c++·算法
笨笨饿8 小时前
140_AI新手村MCP与Skills是干嘛的
开发语言·人工智能·python·stm32·单片机·嵌入式硬件·物联网
YOLO数据集集合8 小时前
EvoAgent:面向PR研发治理的自进化Multi-Agent Harness系统
java·开发语言·目标检测·agent·自进化