变量
一、声明变量
- var 标准格式声明
var 变量名 变量类型
1 | var name string |
- 批量格式
1 | var ( |
二、变量初始化
golang 变量初始化具有默认值,整数 浮点默认值是0;字符串默认值是空字符串;布尔默认值true;切片、函数、指针默认值为nil
- 标准格式
var 变量名 类型 = 表达式
1 | var name string = "lisong" |
- 编译器推导
1 | var name = "lisong" |
- 短变量声明并初始化
1 | name := "lisong" |
注意:=和=的区别, := 表示身边并初始化,= 只表示赋值
三、多个变量同时赋值
1 | var name,age = "lisong",28 |
四、匿名变量
1 | func GetData(){ |
数据类型
Go语言的数据类型包含基本的整型,浮点型,布尔型,字符串,还有切片,结构体,函数,map,通道(channel),切片有着比指针的便利性,但比指针安全,切片可以进行安全切高效的内存操作。
1. 整型(int)
整型分类
- 按长度分类: int8/int16/int32/int64
按对应的无符号整型: uint8/int16/int32/int64
其中,uint8就是我们熟知的byte型,int16对应C语言中的short型,int64对应C语言中的long型
特点:
- 根据平台自动匹配int/uint
2. 浮点型(float)
golang 支持两种浮点型数:float32/float64
- float32 最大值常量定义math.MaxFloat32
- float64 最大值常量定义math.MaxFloat64
3. 布尔型(bool)
1 | var n bool = true |
4. 字符串(string)
双引号””表示字符串;反引号``表示多行字符串
示例:
1
2
3
4
5name := "lisong"
content := `
I'm coder,
love coding
`字符串转义符
转义符 | 含义 |
---|---|
\r | 回车符 |
\n | 换行符 |
\t | 制表符 |
\‘ | 单引号 |
\“ | 双引号 |
\\ | 反斜杠 |
5. 字符(byte)
GO语言字符分为2中
- 一种是uint8类型,或者叫做byte型,代表ASCII码的一个字符
- 另一种是rune类型,代表一个UTF-8字符,当处理中文或者日文的时候需要用到rune类型,rune类型实际上是一个int32
- 示例:
1 | var a byte = 'a' |
6. 切片
1 | slice := make([]int, 3) // 创建切片 |
- 本文作者: ChuLinx
- 本文链接: http://yoursite.com/2019/12/10/Go语言复习笔记——基本语法一之变量数据类型/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!