Golang Study Notes [5] integer and golang Study Notes integer
Golang has many integer classes, but generally it is better to use int or uintt,
Package mainimport ("fmt" "unsafe") func main () {var i1 int8 = 1 // 1 bytevar i2 int16 = 2 // 2 bytevar i3 = 3 // 4 bytevar i4 int64 = 4 // 8 bytevar i5 int = 5 // 32-bit: 4 64-bit: 8var i6 uint8 = 1 // 1 bytevar i7 uint16 = 2 // 2 bytevar i8 uint32 = 3 // 4 bytevar i9 uint64 = 4 // 8 bytevar i10 uint = 5/32 bit: 4 64-bit: 8var i11 byte = 1 // equivalent to uint8 1 bytevar i12 rune = 3 // equivalent to int32 4 bytevar i13 uintptr = 6 // 32-bit: 4 64-bit: 8fmt. println (unsafe. sizeof (i13) // 8fmt. println (i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13) // 1 2 3 4 5 1 3 4 5 5 1 6}
Int type and int32 or int64 cannot be directly added or subtracted. Only the same type (the same type name) can be added or subtracted. golang does not support implicit conversion.
package mainfunc main() {var i1 int = 1var i2 int32 = 2var i3 int64 = 3i4 := i1 + i2 }
.\main.go:9: invalid operation: i1 + i2 (mismatched types int and int32)
Use int (variable name forced conversion)
package main
import (
"fmt"
)
func main() {
var i1 int = 1
var i2 int32 = 2
var i3 int64 = 3
I4: = i1 + int (i2) // int32 is forcibly converted to int
I5: = i1 + int (i3) // forcibly convert int64 to int
fmt.Println(i4, i5)
}