变量定义
1、使用var关键字(变量类型写在变量名之后)
-
var a, b, c bool
-
var s1, s2 string = “hello”, “world”
-
可定义在函数体内或直接定义在包内
-
使用var()集中定义变量
var ( a, b, c)
2、编译器自动识别类型
- var a, b, i, s1, s2 = true, false, 1, “hello”, “world”
3、使用:=定义
- a, b, i, s1, s2 := true, false, 1, “hello”, “world”
- 只能在函数体内定义使用
命名规则:一个名字必须以一个字母(Unicode字母)或下划线开头,后面可以跟任意 数量的字母、数字或下划线。大写字母和小写字母是不同的。关键字不能用于自定义名字,只能在特定语法结构中使用。
Go语言中不存在 未初始化的变量
类型必须完全匹配,nil可以赋值给任何指针或引用类型的变量
25个关键字
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
内建常量
true, false, iota, nil
内建变量类型
1、bool, string
2、(u)int, (u)int8, (u)int16, (u)int32, (u)int64, uintptr(指针)
3、byte, rune(字符)
4、float32, float64, complex64, complex128
5、error
内建函数
1、make, len, cap, new, append, copy, close, delete
2、complex, real, imag
3、panic, recover
强制类型转换
类型转换是强制的
var a, b int = 3, 4
var c int = int(math.Sqrt(float64(a * a + b * b)))
fmt.Println(c)
常量、枚举定义
1、使用const关键字
2、const数值可作为各种类型使用
// 常量定义
const fileName = "abc.txt"
const a, b = 3, 4
// 枚举定义
const (
cpp = iota
_
python
golang
javascript
)