Sobes.tech
Junior

What is the difference between the uint and int types in the Go language?

sobes.tech AI

Answer from AI

The uint and int types in Go represent integer data types, but differ in the range of values they can represent and their meaning (signed/unsigned).

int (signed integer):

  • Can store both positive and negative numbers, as well as zero.
  • Size in bits (and consequently, the range) depends on the computer architecture (32 or 64 bits). On a 32-bit architecture, it is 32 bits; on a 64-bit architecture, it is 64 bits.
  • Range: from -2<sup>n-1</sup> to 2<sup>n-1</sup> - 1, where n is the number of bits.

uint (unsigned integer):

  • Can only store non-negative numbers, starting from zero.
  • Size in bits also depends on the computer architecture (32 or 64 bits) and matches the size of int.
  • Range: from 0 to 2<sup>n</sup> - 1, where n is the number of bits.

The main difference is that int uses one bit to represent the sign (positive or negative number), whereas uint uses all bits to represent the magnitude of the number. This allows uint to store a maximum positive range twice as large as int of the same size.

When choosing between int and uint, consider:

  • Whether the number might be negative. If yes, use int.
  • Whether a maximum positive range is needed. If yes, and negative values are not required, uint might be suitable.
  • The uint type is often used for bit masks, identifiers, sizes, or quantities that by their nature cannot be negative.
// int can be negative
var signedInt int = -10
// uint cannot be negative
// var unsignedInt uint = -10 // Compilation error

// Maximum values (on a 64-bit system)
// fmt.Println(math.MaxInt64)  // 9223372036854775807
// fmt.Println(math.MaxUint64) // 18446744073709551615 (about twice as large)

// Implicit conversion is not possible between int and uint
var a int = 5
var b uint = 5
// if a == b { ... } // Error: type mismatch without explicit conversion

// Explicit conversion
var c int = 10
var d uint = uint(c)

var e uint = 20
var f int = int(e)