Go速成-常量

1.常量的定义

Go语言常量,定义的值是不能进修修改的,定义常量就是const,常量定义建议全部大写

Go 复制代码
	const PI float32 = 3.1415946 //显式定义
Go 复制代码
	const (
		x int = 16
		y
		s = "abc"
		z
	)
    fmt.Print(x,y,s,z)

在定义常量的时候如果没有声明值,就会沿用上面的值,常量类型只可以定义bool,数值类型,字符串,常量没有必须使用的要求。

2iota常量的使用

2.1common

iota是Go中一个特殊的常量,其实就是一个自增的常量,可以理解为计数器默认是0开始,可以自定义

Go 复制代码
	const (
		ERR1 = iota
		ERR2
		ERR3
		ERR4
	)

	fmt.Print(ERR1,ERR2,ERR3,ERR4)

2.2special

Go 复制代码
	const (
		hello1 = iota + 1 //1
		hello2 			 //2
		hello3 = "hello" //两个字符串的值是3
		hello4
		hello5 = iota 	// 4,显示回复iota
	)
	fmt.Println(hello1,hello2,hello3,hello4,hello5)

因为hello4未声明,所以hello3==hello4所以他们两个值相同,然后iota常量的值也就相同,如果中断了iota那么也要显示的恢复,自增类型就是int,iota可以简化iota的定义。

每次const代码块出现的时候iota初始化为0,相当于const的内部变量

3匿名变量

Go 复制代码
//声明方式
	var _ int // _代表变量名

匿名变量可以不使用。

相关推荐
为思念酝酿的痛5 小时前
POSIX信号量
linux·运维·服务器·后端
小羊在睡觉5 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
AI玫瑰助手6 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车6 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋6 小时前
C++14特性
开发语言·c++·c++14特性
swipe6 小时前
Neo4j + Graph RAG 医疗知识图谱工程实践:患者教育问答真正需要的是“关系可追溯”
后端·langchain·llm
源码宝7 小时前
MES系统源码:Java8 + SpringBoot2.7 + MySQL8 + Redis,后端源码清爽易扩展
java·后端·源码·springboot·mes系统·源码二开·mes源码
JAVA社区7 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
弥树子7 小时前
踩坑记录:服务器内网调用接口,真实请求URL与官方公开URL不一致问题排查
开发语言·php
金銀銅鐵7 小时前
[Java] 如何理解 class 文件中方法的 descriptor?
java·后端