Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 147 Β· Variables and Types

Basic Types

A tour of Go basic types - bool, sized and unsigned integers, byte and rune, floats, complex numbers, strings, unsafe.Sizeof and overflow wraparound.

Every value in Go has a type, and the type decides what the value can hold and which operations are allowed. Go is statically typed: the compiler knows the type of every expression before the program runs, and it refuses to compile code that mixes types carelessly. That's one reason Go programs tend to have fewer surprises at run time.

Go's built-in basic types fall into four families: booleans, numbers (integers, floating-point numbers and complex numbers), strings, and the character-like aliases byte and rune. This lesson introduces them all, shows how big they are, explains how to choose between them, and demonstrates what happens when a number gets too large for its type. Later lessons go deeper into numbers and math, strings and runes and type conversion.

The list of basic types

Family Types
Boolean bool
Signed integers int, int8, int16, int32, int64
Unsigned integers uint, uint8, uint16, uint32, uint64, uintptr
Aliases byte (= uint8), rune (= int32)
Floating-point float32, float64
Complex complex64, complex128
Text string

The number in a name is the size in bits. An int8 has 8 bits, so it can store 256 different values; an int64 has 64 bits. The types int, uint and uintptr are special: their size depends on the platform. On a 64-bit computer (which includes our server and almost every machine you will use today) they are 64 bits wide.

Booleans

A bool is either true or false. Comparisons produce booleans, and if and for require one: Go never treats 0, "" or nil as false.

Go Booleans and comparisons

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The operators are && (and), || (or) and ! (not). You can't convert a number to a bool or the other way around; if you need that, write a comparison such as n != 0.

Integers

Go has ten sized integer types plus int and uint. Unless you have a reason to pick another, use int for counts, indexes, lengths and general whole-number math. The standard library uses it too (len returns an int), so staying with int avoids conversions.

Each type has a fixed range. For an n-bit signed type the range is βˆ’2^(nβˆ’1) to 2^(nβˆ’1)βˆ’1; for unsigned it is 0 to 2^nβˆ’1. The math package has constants for the limits:

Go The range of each integer type

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

(uint64(math.MaxUint64) needs the conversion because a bare constant that large doesn't fit the int that Println would otherwise choose.)

Integer literals can be written in several bases. Underscores are allowed for readability, and the prefixes are 0b (binary), 0o or 0 (octal) and 0x (hexadecimal):

Go Integer literals in different bases

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

When to use the sized types

Pick a sized type when the size matters: uint8 (byte) for raw data, int64 for timestamps and database IDs that can exceed 2 billion, int32 for compact arrays of numbers, uint32 for hashes, and so on. Sized types also appear in file formats and network protocols, where a field is defined as "a 16-bit unsigned number".

The unsafe.Sizeof function reports a type's size in bytes. It is a compile-time constant:

Go Sizes of the basic types

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A string is 16 bytes on a 64-bit machine because the variable holds only a pointer to the text and its length; the characters themselves live elsewhere. Strings, bytes and runes explains this. The unsafe package is named that way because it can bypass Go's safety rules, but Sizeof itself is harmless. Memory layout uses it to explain struct padding.

Overflow wraps around

When arithmetic on a variable produces a value that doesn't fit its type, Go doesn't crash and doesn't promote the result to a bigger type. The bits that don't fit are simply discarded, so the number wraps around:

Go Integer overflow wraps around

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The counter small goes 251, 252, ..., 255, then back to 0, 1, 2. Unsigned types wrap from their maximum to 0, and signed types wrap from the largest positive value to the most negative one. This is well-defined behavior in Go, not undefined behavior as in C, and it is useful for hash functions and random-number generators. But it is also a classic source of bugs when you count things in a type that's too small.

Overflow of variables is silent. If a calculation might exceed your type (a sum of many int32 values, a factorial, a price multiplied by a quantity), widen to int64, check the range yourself, or use the math/big package, which the numbers lesson introduces.

Constants are different: the compiler checks them, and var x int8 = 200 simply doesn't compile (see constants).

Floating-point numbers

float64 (64 bits, about 15–16 significant digits) is the default for fractional numbers and the type almost all of the math package works with. float32 (about 7 digits) saves memory in large arrays and graphics code but is rarely the right choice otherwise.

Go float64 and float32

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

That 0.1 + 0.2 is not exactly 0.3 is true in every language that uses IEEE 754 numbers. Never compare floating-point values with == after calculations, and never store money in a float64. Use integers of the smallest unit (cents) instead. Numbers and math covers this in detail, along with NaN and infinity.

Complex numbers

Go has built-in support for complex numbers. complex128 is made of two float64 values, and complex64 of two float32. You write the imaginary part with an i suffix and use the built-in functions real, imag and complex:

Go Complex numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Complex types are used for signal processing, fractals and engineering code, so most programs never touch them. The standard math/cmplx package has functions such as Abs and Sqrt for them.

Strings

A string is an immutable sequence of bytes, usually holding UTF-8 text. String literals use double quotes (with escape sequences like \n) or backticks (raw, no escapes). You can join strings with + and get the length in bytes with len:

Go Strings at a glance

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Indexing a string gives you a byte (a number), not a character, and strings can't be modified in place. Those points matter once your text contains anything beyond English letters, so they get a full lesson of their own: strings, bytes and runes.

byte and rune

Go has two aliases that tell the reader what a number means:

  • byte is an alias for uint8: use it for raw data and for the individual bytes of a string.
  • rune is an alias for int32: it holds one Unicode code point, which is roughly "one character". A rune literal is written in single quotes: 'a', 'Γ©', 'δΈ–'.

An alias is the same type with another name, so byte and uint8 can be used interchangeably, and %T prints uint8 and int32:

Go byte and rune

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Choosing a type

A short checklist covers nearly every decision:

  • Whole numbers: int. Use int64 or uint64 when the value can exceed 2 billion and you can't count on a 64-bit platform, and uint32/uint8 where a format or protocol says so.
  • Fractional numbers: float64.
  • Money and exact decimals: integers in the smallest unit, or a decimal library.
  • Raw bytes: byte and []byte. Characters: rune. Text: string.
  • True/false: bool.

Mixing types is not allowed: adding an int to an int64, or a float64 to an int, is a compile error. The next section of the course shows how to convert values explicitly.

Go Mixing types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler stops with:

TEXT
./main.go:8:14: invalid operation: count * price (mismatched types int and float64)

The fix is float64(count) * price, which type conversion explains.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. Which type should you normally use for a loop counter or the length of a list?

    int is the default integer type. len returns an int and slices are indexed with ints, so using int avoids conversions.
  2. 2. What does this print? var n uint8 = 255; n++; fmt.Println(n)

    Arithmetic on integer variables wraps around. 255 plus 1 does not fit in 8 bits, so the result is 0.
  3. 3. What is byte in Go?

    byte is another name for uint8. rune is the alias for int32.
  4. 4. Does var a int = 3; var b int64 = 4; fmt.Println(a + b) compile?

    Go has no implicit numeric conversions. int and int64 are distinct types even on a 64-bit machine, so you must convert one of them.
  5. 5. What is the type of x in x := 'a'?

    A character literal in single quotes is an untyped rune constant, and := gives it the default type rune, which is int32.

Summary

  • Go's basic types are bool, the integers (int, int8...int64, uint...uint64, uintptr), byte (= uint8), rune (= int32), float32/float64, complex64/complex128 and string.
  • Use int for whole numbers, float64 for fractions, string for text and bool for conditions; choose sized types only when the size matters.
  • unsafe.Sizeof reports sizes in bytes; int is 64 bits on 64-bit platforms.
  • Integer overflow on variables wraps around silently; constants that don't fit are compile errors.
  • Floating-point numbers are approximate, so compare with care and never use them for money.
  • Different numeric types never mix automatically; you convert explicitly.

Next: Numbers and Math