Choose signed and unsigned integers in Go
Integer ranges
An integer stores a whole number. Signed types int8, int16, int32, int64 represent negative and nonnegative numbers. Unsigned types uint8, uint16, uint32, uint64 represent nonnegative numbers only. The number in each name is its bit width. For example int8 holds -128 through 127; uint8 holds 0 through 255. Use int for ordinary counts unless a fixed width is needed. Its width, like uint, is either 32 or 64 bits depending on the implementation.
package main
import "fmt"
func main() { var temperature int8 = -12 var brightness uint8 = 255 fmt.Println(temperature, brightness)}The output is -12 255. A negative temperature requires a signed type. A color channel bounded to 0–255 fits uint8. Do not select unsigned solely to validate input: a numeric conversion can wrap a negative value into a large unsigned value.
Aliases for bytes and code points
package main
import "fmt"
func main() { var channel byte = 128 var letter rune = 'A' fmt.Println(channel, letter)}The output is 128 65. byte is an alias for uint8; rune is an alias for int32 and often represents a Unicode code point. A single-quoted rune literal represents a code point; Println prints its numeric value here. uintptr is a special unsigned integer type for storing pointer bit patterns; ordinary counts should not use it. A constant such as 256 cannot be assigned to uint8 because it is outside the range.
Try it locally
Declare a signed int16 balance of -300 and a byte opacity of 200. Print both. Expected: -300 200. Hint: keep each value within its type range.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Constants and Basic Types 02: Choose signed and unsigned integers in Go
Check the lesson objective before moving on.
Which type can hold -1 and 100?
Which value cannot be assigned directly to uint8?