Go语言学习-const的使用

Go语言学习-const的使用

基本介绍

1. 常量不能修改

const类似于java中的常量声明,看看基本语法

const name = "zs"

相当于定义个name常量,这个name是不能被修改的

当我们尝试去修改一个const 修饰的常量时:

// Cannot assign to name,下面就是无法修改常量值
name = "ls"

这个时候编译器时会报错的,会给出提示:Cannot assign to name

2. 常量必须初始化

看下这个声明:

// Missing value in the const declaration
const weight float64

这种情况也是不允许存在的,编译器会提示报错,const 声明的变量需要初始化

3. const配合iota使用

// iota,必须和const一起使用,iota是按行数增加的
const (
  // iota = 0,然后依次往下递增
  age1 = iota
  // iota = 1
  age2
  // iota = 2
  age3
) 

iota :可以理解行计数器,它时从 0 开始递增的,每一行对应一个值,跟每行有几个变量没什么关系;

const (
  // 这里 a, b都在一行,所以 iota的值都是一样的
  a, b = iota + 1, iota + 2 // a = 1, b = 2
  c, d                      // c = 2, d = 3
  e, f                      // e = 3, f = 4

  g, h = iota * 1, iota * 2 // g = 3, h = 6
  i, j                      // i = 4, j = 8
)

这段代码可以验证,iota 的值与每行有多少变量无关;

全部代码

package main

import "fmt"

// 相当于定义了一个常量值
const name = "zs"

// Missing value in the const declaration
// const weight float64

// iota,必须和const一起使用,iota是按行数增加的
const (
  // iota = 0,然后依次往下递增
  age1 = iota
  // iota = 1
  age2
  // iota = 2
  age3
)

const (
  // 这里 a, b都在一行,所以 iota的值都是一样的
  a, b = iota + 1, iota + 2 // a = 1, b = 2
  c, d                      // c = 2, d = 3
  e, f                      // e = 3, f = 4

  g, h = iota * 1, iota * 2 // g = 3, h = 6
  i, j                      // i = 4, j = 8
)

func main() {
  fmt.Println(name)
  // Cannot assign to name,下面就是无法修改常量值
  // name = "ls"

  fmt.Println("age1 =", age1, " age2 =", age2, " age3 =", age3)

  fmt.Println("a =", a, " b =", b)
  fmt.Println("c =", c, " d =", d)
  fmt.Println("e =", e, " h =", h)
  fmt.Println("i =", i, " j =", j)
}

输出结果:

zs
age1 = 0  age2 = 1  age3 = 2
a = 1  b = 2
c = 2  d = 3
e = 3  h = 6
i = 4  j = 8
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值