常量和变量

常量和变量

文件名&关键字&标识符

  1. 所有go源码以.go结尾
  2. 标识符以字母或下划线开头,大小写敏感,比如:
a. boy   √
b. Boy   √
c. a+b   x
d. Oboy  √
e. _boy  √
f. =_boy  x
g. _      √  //特殊的标识符,a,_,b,意思是不取值
  1. _是特殊标识符,用来忽略结果
  2. 保留关键字
breakdefaultfuncinterfaceselect(用在chann管道里面)
casedefergomapstruct
chanelsegotopackageswitch
const(声明一个常量)fallthoughifrangetype
continueforimportreturnvar
  1. 37和保留字
    Constants:    true  false  iota  nil

        Types:    int  int8  int16  int32  int64  
                  uint  uint8  uint16  uint32  uint64  uintptr
                  float32  float64  complex128  complex64
                  bool  byte  rune  string  error

    Functions:   make  len  cap  new  append  copy  close  delete
                 complex  real  imag
                 panic  recover

常量

1.常量使用const修饰,代表永远是只读的,不能修改
2.const只能修饰boolean,number(int类型,浮点类型,complex)和string
3.语法: const identifier [type] = value,其中type可以省略
//举例:
const b string = "hello world"
const b = "hello world"
const Pi = 3.1415926
const a = 9/3
const c = getValue() //这是错误的,不能是一个函数

4.比较优雅的写法:
const(
    a=0
    b=1
    c=2
)
5.更专业的写法:
const(
    a=iota
    b //1
    c //2
)

iota的使用

iota是go语言的常量计数器,只能在常量的表达式中使用。

iota在const关键字中出现时将被重置为行索引值。const中每新增一行常量声明将使iota计数一次(iota可理解为const语句块中的行索引)。 使用iota能简化定义,在定义枚举时很有用。

const (
	a = 3.2323232
	c = iota //1
	d    //2
	e = iota //3
	f   //4
)

// 多个常量声明在一行
const (
	d1, d2 = iota + 1, iota + 2 // d1:1 d2:2

	d3, d4 = iota + 1, iota + 2 // d3:2 d4:3
)
const (
	a, b = iota, iota //0 0 
	d    = iota // 1
)
iota的数量级使用
const (
	_  = iota             // 0
	KB = 1 << (10 * iota) // 1向左边移动10位,变成1000000000,2的10次方,也就是1024
	MB = 1 << (10 * iota) // 1向左边移动20位
	GB = 1 << (10 * iota)
	TB = 1 << (10 * iota)
	PB = 1 << (10 * iota)
)

变量

var (
    a int //默认是0
    b string //默认是""
    c bool //默认是false
    d int = 8
    e string="hello world"
)

var (
    a int //默认是0
    b string //默认是""
    c bool //默认是false
    d = 8  //可以不加类型,go会自动推导出值的类型
    e ="hello world"
)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值