The difference between int, int8, int16, int32, int64 and uint in Golang

The difference between int, int8, int16, int32, int64 and uint in Golang

foreword

When learning the go language, when doing algorithm problems, you will often encounter various int types in the go language. Why are there types of int, int8, int16, etc.? Why not just an int type like java?

test

unsafe.Sizeof() only returns the size of the data type, regardless of the size of the reference data, the unit is Byte

package main

import (
	"fmt"
	"unsafe"
)

func main() {
    
    
	var a int = 1
	var b int8 = 2
	var c int16 = 3
	var d int32 = 4
	var e int64 = 5
	fmt.Println(unsafe.Sizeof(a))
	fmt.Println(unsafe.Sizeof(b))
	fmt.Println(unsafe.Sizeof(c))
	fmt.Println(unsafe.Sizeof(d))
	fmt.Println(unsafe.Sizeof(e))
}

result

F:\go\bin\go.exe build -o C:\Users\wang3\AppData\Local\Temp\GoLand\___go_build_test_go.exe G:\Gospace\leetcode\test.go #gosetup
C:\Users\wang3\AppData\Local\Temp\GoLand\___go_build_test_go.exe
8
1
2
4
8

in conclusion

  • The size of the int type is 8 bytes
  • int8 type size is 1 byte
  • int16 type size is 2 bytes
  • int32 type size is 4 bytes
  • int64 type size is 8 bytes

Let's take a look at the official documentation,
int is a signed integer type that is at least 32 bits in size. It is a distinct type, however, and not an alias for, say, int32.
which means that int is a signed integer type of at least 32 bits. However, it's a different type, not an alias for int32. int and int32 are two different things.
uint is a variable sized type, on your 64 bit computer uint is 64 bits wide.
uint is a variable-size type, and on a 64-bit machine, uint is 64 bits wide. Both uint and uint8 are unsigned int types. The length of the uint type depends on the CPU. If it is a 32-bit CPU, it is 4 bytes, and if it is a 64-bit CPU, it is 8 bytes.

Summarize

The size of the int in the go language is related to the number of bits in the operating system. If it is a 32-bit operating system, the size of the int type is 4 bytes. If it is a 64-bit operating system, the size of the int type is 8 bytes

Guess you like

Origin blog.csdn.net/a6661314/article/details/122798788