Go语言的整数类型用于存放整数值,如12,-34,5678等
类型 | 有无符号 | 占用空间 | 表数范围 | 备注 |
---|---|---|---|---|
int8 | 有 | 1字节 | -128~127 | |
int16 | 有 | 2字节 | -215~215-1 | |
int32 | 有 | 4字节 | -231~231-1 | |
int64 | 有 | 8字节 | -263~263-1 | |
uint8 | 无 | 1字节 | 0~255 | |
uint16 | 无 | 2字节 | 0~216-1 | |
uint32 | 无 | 4字节 | 0~232-1 | |
uint64 | 无 | 8字节 | 0~264-1 | |
int | 有 | 32位系统4个字节 64位系统8个字节 | -231~231-1 -263~263-1 | |
uint | 无 | 32位系统4个字节 64位系统8个字节 | 0~232-1 0~264-1 | |
rune | 有 | 与int32一样 | -231~231-1 | 表示一个Unicode码,存储多字节 |
byte | 无 | 与uint8等价 | 0~255 | 存储英文字符时使用 |
// int8
fmt.Println("MaxInt8:", math.MaxInt8)
fmt.Println("MinInt8:", math.MinInt8)
// int16
fmt.Println("MaxInt16:", math.MaxInt16)
fmt.Println("MinInt16:", math.MinInt16)
// int32
fmt.Println("MaxInt32:", math.MaxInt32)
fmt.Println("MinInt32:", math.MinInt32)
// int64
fmt.Println("MaxInt64:", math.MaxInt64)
fmt.Println("MinInt64:", math.MinInt64)
// uint8
fmt.Println("MaxUint8:", math.MaxUint8)
// uint16
fmt.Println("MaxUint16:", math.MaxUint16)
// uint32
fmt.Println("MaxUint32:", math.MaxUint32)
// uint64
fmt.Println("MaxUint64:", uint64(math.MaxUint64))
image-20210326001627531.png
5.5.2 整数类型的使用细节
Go语言各整数类型分为:有符号(int)与无符号(uint)
Go语言整型默认声明为int型
如何在程序中查看某个变量的字节大小和数据类型
Go语言中整型变量在使用时,遵守保小不保大的原则,即:在保证程序正确运行下,尽量使用占用空间小的数据类型。如:年龄
bit:计算机中最小的存储单位。byte:计算机中基本存储单元。1 byte = 8 bit
package main
import (
"fmt"
"unsafe"
)
func main() {
var n1 = 100
fmt.Printf("n1的类型%T\n", n1)
var n2 int64 = 100
fmt.Printf("n2的类型%T,n2占用的字节数是%d\n", n2, unsafe.Sizeof(n2))
var age byte = 90
fmt.Printf("age的类型%T,age占用的字节数是%d\n", age, unsafe.Sizeof(age))
}
运行效果如下图:
image-20210401142526485.png
[上一篇:八、浮点类型(待更新)]