Welcome To Golang By Example

Know Size and Range of int or uint in Go (Golang)

Table of Contents

Overview

Size and range of int and uint in go is platform-dependent meaning that the size and range depend whether the underlying platform is 32-bit or a 64-bit machine.

Size Table

TypeSize (32 bit machine)Size (64 bit machine)
int32 bits or 4 byte64 bits or 8 byte
uint32 bits or 4 byte64 bits or 8 byte

Range Table

TypeSize (32 bit machine)Size (64 bit machine)
int-231 to 231 -1-263 to 263 -1
uint0 to 232 -10 to 264 -1

Know Size and Range

const uintSize = 32 << (^uint(0) >> 32 & 1) // 32 or 64

Once the size is known, the range can be deduced based upon size. See the below code for printing size.

package main

import (
    "fmt"
    "math/bits"
    "unsafe"
)

func main() {
    //This is computed as 
    //const uintSize = 32 << (^uint(0) >> 32 & 1) // 32 or 64
    sizeInBits := bits.UintSize
    fmt.Printf("%d bits\n", sizeInBits)

    //Using unsafe.Sizeof() function. It will print size in bytes
    var a int
    fmt.Printf("%d bytes\n", unsafe.Sizeof(a))

    //Using unsafe.Sizeof() function. It will print size in bytes
    var b uint
    fmt.Printf("%d bytes\n", unsafe.Sizeof(b))
}

Output:

64 bits
8 bytes
8 bytes