22
【Go从学会到学废】(三) 变量和常量
source link: https://studygolang.com/articles/31176
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Go声明变量方法:
Go 语言变量名由字母、数字、下划线组成,其中首个字符不能为数字。
声明变量的一般形式是使用 var 关键字:
第一种声明变量方法:
var identifier type var identifier1,identifier2,identifier3 type
var s0 string s0 = "Hello" var s1 string = "Hello" var s2, s3 string = "Hello", "World" var i1 int = 10 var i2, i3, i4 int = 1, 2, 3 var b1 bool = true var b2, b3 bool = true, false
也可以这样
var ( s0 string s1 string s2, s3 string i1 int i2, i3, i4 int b1 bool b2, b3 bool )
==注:==
- ==声明了变量一定要使用==
- ==与
C/C++,Java
不同的是,GO
类型在前,变量名在后==
第二种声明变量方法:
根据值自行判定变量类型
var s1 = "Hello" var s2, s3 = "Hello", "World" var i1 = 10 var i2, i3, i4 = 1, 2, 3 var b1 = true var b2, b3 = true, false
第三种声明变量方法:
省略 var
, 使用 :=
s1 := "Hello" s2, s3 := "Hello", "World" i1 := 10 i2, i3, i4 := 1, 2, 3 b1 := true b2, b3 := true, false
-
==左侧如果不是声明新的变量,就会报错==
-
==如果在相同的代码块中,我们不可以再次对于相同名称的变量使用初始化声明==
-
使用起来简洁,高效
var a int a := 1
或
s := "Hello" s := "World" var s
都是错的
匿名变量
可以用 _
作为匿名变量,意味着 只写 或者 占位符
_, i1 := 10, 9 s1, _, _ := "Hello", "World",""
Go声明变量方法:
声明变量的一般形式是使用 const关键字:
const s1 string = "Hello" const s2 = "World" const b1 bool = true const b2 = false const i1 int = 1 const i2 = 0
或者
const ( s1 string = "Hello" s2 = "World" b1 bool = true b2 = false i1 int = 1 i2 = 0 )
==注:==
- ==常量声明必须初始化,但不一定要使用==
itoa
const 内的 iota是golang语言的常量计数器,只能在常量的表达式中使用,,即const内。iota==在const关键字出现时将被重置为0==(const内部的第一行之前),const中==每新增一行常量==声明将使iota计数一次。可以参照行号理解,也就是说将iota理解为const语句块中的行索引。类似于枚举
const a = iota // a=0 const b = iota //b=0 const ( c = iota //c=0 d //d=1 e, f = iota + 0, iota + 0 //e=2,f=2 )
有疑问加站长微信联系
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK