go同時提供了有符号和無符号的整數類型
有符号
// int8 is the set of all signed 8-bit integers.
// Range: -128 through 127.
type int8 int8
// int16 is the set of all signed 16-bit integers.
// Range: -32768 through 32767.
type int16 int16
// int32 is the set of all signed 32-bit integers.
// Range: -2147483648 through 2147483647.
type int32 int32
// int64 is the set of all signed 64-bit integers.
// Range: -9223372036854775808 through 9223372036854775807.
type int64 int64
無符号
// uint8 is the set of all unsigned 8-bit integers.
// Range: 0 through 255.
type uint8 uint8
// uint16 is the set of all unsigned 16-bit integers.
// Range: 0 through 65535.
type uint16 uint16
// uint32 is the set of all unsigned 32-bit integers.
// Range: 0 through 4294967295.
type uint32 uint32
// uint64 is the set of all unsigned 64-bit integers.
// Range: 0 through 18446744073709551615.
type uint64 uint64
和平台相關
無固定大小,和特定平台相關,32位平台就是32位,64位平台就是64位
// 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.
type int int
// uint is an unsigned integer type that is at least 32 bits in size. It is a
// distinct type, however, and not an alias for, say, uint32.
type uint uint
别名
一般隻有處理字元的時候使用
// byte is an alias for uint8 and is equivalent to uint8 in all ways. It is
// used, by convention, to distinguish byte values from 8-bit unsigned
// integer values.
type byte = uint8
// rune is an alias for int32 and is equivalent to int32 in all ways. It is
// used, by convention, to distinguish character values from integer values.
type rune = int32
針對指針
還有一種無符号的整數類型uintptr,沒有指定具體的bit大小但是足以容納指針。
uintptr類型隻有在底層程式設計時才需要,特别是Go語言和C語言函數庫或作業系統接口互相動的地方。
// uintptr is an integer type that is large enough to hold the bit pattern of
// any pointer.
type uintptr uintptr
零值和預設類型
func TestInt1(t *testing.T) {
// 零值0
var num1 int8
fmt.Println(num1) // 0
// 預設類型int
num2 := 10
fmt.Println(reflect.TypeOf(num2), num2) // int 10
}
有符号和無符号的選擇
雖然go同時提供了有符号和無符号的整數類型,但是大多數情況下,我們編碼過程中還是更加傾向于使用有符号的int類型。比如說數組的長度,雖然不可能為負數,但是内置的len函數傳回的還是一個有符号的int,這樣做是有原因的,看以下代碼:
func TestInt1(t *testing.T) {
medals := []string{"gold", "silver", "bronze"}
for i := len(medals) - 1; i >= 0; i-- {
fmt.Println(medals[i]) // "bronze", "silver", "gold"
}
}
如果說len傳回的是一個無符号的整數類型,那麼i也是一個無符号的整數類型,i–一直不會小于0,則i >= 0一直為真
邊界值
// Integer limit values.
const (
MaxInt8 = 1<<7 - 1
MinInt8 = -1 << 7
MaxInt16 = 1<<15 - 1
MinInt16 = -1 << 15
MaxInt32 = 1<<31 - 1
MinInt32 = -1 << 31
MaxInt64 = 1<<63 - 1
MinInt64 = -1 << 63
MaxUint8 = 1<<8 - 1
MaxUint16 = 1<<16 - 1
MaxUint32 = 1<<32 - 1
MaxUint64 = 1<<64 - 1
)
範圍溢出,不會報錯
func TestInt(t *testing.T) {
// 上限溢出
var num1 int8 = math.MaxInt8
fmt.Println(num1) // 127
num1++
fmt.Println(num1) // -128
// 下限溢出
var num2 int16 = math.MinInt16
fmt.Println(num2) // -32768
num2--
fmt.Println(num2) // 32767
// 無符号整數
var i uint8 = 0
i--
fmt.Println(i) // 255
}