go语言(三)常量和iota

常量

和php定义一样,一次赋值后不可重复赋值, 可以批量声明,

package main

import "fmt"

const pi = 3.1415926

const (
	STATUSOK = "200"
	NOTFOUND = 404
)

// 批量常量赋值, 如果某一行声明后没有赋值,默认和上一行一致
const (
	n1 = 200
	n2 = 100
	n3
)

func main() {
	fmt.Println(pi)
	fmt.Printf("当前服务器状态码:%s", STATUSOK)

	fmt.Println("n1", n1)
	fmt.Println("n2", n2)
	fmt.Println("n3", n3)
}

iota

iota可以认为是声明常量行数的索引, const出现的时候,iota会置为0

package main

import "fmt"

// iota:类似于枚举
const (
	a1 = iota
	a2
	a3
)

const (
	b1 = iota
	b2
	_
	b3
)

// 插队
const (
	c1 = iota
	c2 = 100
	c3 = iota
	c4
)

// 多个常量声明在一行,iota相当于声明常量行数的索引值, 多个常量在一行声明,iota不会增加, 所以d1 = 1, d2 = 2, d3 = 2, d4 = 3
const (
	d1, d2 = iota + 1, iota + 2
	d3, d4 = iota + 1, iota + 2
)

// 定义数量级
const (
	_ = iota
	KB = 1 << (10 * iota)		// << 想当于向左移动一定的位数,  此时iota等于1,也就是1 << 10, 1左移10位,也就是10000000000,二进制换算成10进制,也就是1024
	MB = 1 << (10 * iota)
	GB = 1 << (10 * iota)
	TB = 1 << (10 * iota)
	PB = 1 << (10 * iota)
)

func main() {
	fmt.Println("a1", a1)
	fmt.Println("a2", a2)
	fmt.Println("a3", a3)
	
	fmt.Println("b1", b1)
	fmt.Println("b2", b2)
	fmt.Println("b3", b3)
	
	fmt.Println("c1", c1)
	fmt.Println("c2", c2)
	fmt.Println("c3", c3)
	fmt.Println("c4", c4)
	
	fmt.Println("d1", d1)
	fmt.Println("d2", d2)
	fmt.Println("d3", d3)
	fmt.Println("d4", d4)
}

// a1 = 0, a2 = 1, a3 = 2
// b1 = 0, b2 = 1, b3 = 4  _是匿名常理,当前值被抛弃
// c1 = 0, c2 = 100, c3 = 2, c4 = 3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值