This entry is 第 3 部分,共 3 in the series Go(Golang)学习之路
Table of Contents
Toggle1. 数字类型
1.1 Golang数据类型介绍
- Go语言数据类型分为:基本数据类型和复合数据类型
- 基本数据类型有:整数、浮点型、布尔型、字符串
- 复合数据类型有:数组、切片、结构体、函数、map、通道(channel)、接口
1.2 整数分为两大类
- 有符号整型按长度分为:int8、int16、int32、int64
- 对应的无符号整型:uint8、uint16、uint32、uint64
| 类型 | 范围 | 占用空间 | 有无符号 |
| int8 | (-128 到 127) -2^7 到 2^7-1 | 1个字节 | 有 |
| int16 | (-32768 到 32767) -2^15 到 2^15-1 | 2个字节 | 有 |
| int32 | (-2147483648 到 2147483647) -2^31 到 21^31-1 | 4个字节 | 有 |
| int64 | (-9223372036854775808 到 9223372036854775807) -2^63 到 2^63-1 | 8个字节 | 有 |
| uint8 | (0 到 255) 0 到 2^8-1 | 1个字节 | 无 |
| uint16 | (0 到 65535) 0 到 2^16-1 | 2个字节 | 无 |
| uint32 | (0 到 4294967275) 0 到 2^32-1 | 4个字节 | 无 |
| uint64 | (0 到 18446744073709551615) 0 到 2^64-1 | 8个字节 | 无 |
关于字节:
① 字节也叫Byte,是计算机数据的基本存储单位。
② 8bit(位)=1Byte(字节) 1024Byte(字节)=1KB
③ 1024KB=1MB 1024MB=1GB
④ 1024GB=1TB。在电脑里,一个中文字是占两个字节的。
2. 数字定义
2.1 定义数字类型
package main
import "fmt"
func main() {
var a int8 = 4
var b int32 = 4
var c int64 = 4
d := 4
fmt.Printf("a: %T %v \n", a, a)
fmt.Printf("b: %T %v \n", b, b)
fmt.Printf("c: %T %v \n", c, c)
fmt.Printf("d: %T %v \n", d, d)
}
/*
a: int8 4
b: int32 4
c: int64 4
d: int 4
*/
2.2 reflect.TypeOf查看数据类型
package main
import (
"fmt"
"reflect"
)
func main() {
c := 18
fmt.Println(reflect.TypeOf(c))
}
/*
int
*/
3. 布尔值
- Go语言中,以 bool 类型进行声明布尔型数据,布尔型数据只有true(真)和false(假)两个值。
注意:
① 布尔类型变量的默认值为false。
② Go语言中,不允许将整型强制转换为布尔型。
③ 布尔型无法参与数值运算,也无法与其他类型进行转换。
package main
import (
"fmt"
"unsafe"
)
func main() {
var b = true
fmt.Println(b, "占用字节:", unsafe.Sizeof(b))
}
/*
true 占用字节: 1
*/
As a Newbie, I am continuously browsing online for articles that can be of assistance to me. Thank you
Howdy! This post couldn’t be written any better! Reading through
this post reminds me of my good old room mate! He always kept
chatting about this. I will forward this write-up to him. Fairly certain he will have a good read.
Thank you for sharing!