go 常量使用

常量常量介绍

常量使用const定义
常量在定义的时候,必须初始化
常量不能修改
常量只能修饰bool、数值类型(int,float系列)、string类型
语法:const identifier [type] = value
举例说明,看看下面的写法是否正确:

const name = "tom" //ok
const tax float64 =0.8 //ok
const a int // err
const b = 9/3 //ok
var num = 9
const c = num/3 //err num是变量,不确定的,
const c = getVal() // err

package main

import (
	"encoding/json"
	"fmt"
)

func main(){
	const (
		a = iota
		b = iota
		c,
		d = iota, iota
	)
	fmt.Println(a,b,c,d)
	const (
		a1 = iota
		b1 = iota
		c1 = iota
		d1 = iota
	)
	fmt.Println(a1,b1,c1,d1)
	const (
		a2 = iota
		b2
		c2
		d2
	)
	fmt.Println(a2,b2,c2,d2)
}

输出:

0 1 2 2
0 1 2 3
0 1 2 3

posted @ 2022-03-26 22:52  ty1539  阅读(76)  评论(0编辑  收藏  举报