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
相关推荐
lly2024061 小时前
Bootstrap 警告框
开发语言
2601_949146532 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧2 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX2 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb01032 小时前
C++课后习题训练记录Day98
开发语言·c++
猫头虎3 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
YUJIANYUE3 小时前
PHP纹路验证码
开发语言·php
仟濹4 小时前
【Java基础】多态 | 打卡day2
java·开发语言
孞㐑¥4 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
Re.不晚4 小时前
JAVA进阶之路——无奖问答挑战2
java·开发语言