Go Data Types

In Go languages all variables have a type that can't be changed once established. This makes Go a strongly typed language similar to C++, Rust, Ada and Java. Types are used to verify if expressions or values create the correct data type for specific use-cases at compilation time. This reduce probability of runtime errors.

Go has predefined types, used to declare: constants, variables, parameters and results. Go enable you to declare new data types and composite data types using basic types.

Basic Types

The basic types are the most simple predefined types:

Type Name Keywords Bytes
Boolean bool 1
Integers int, int8, int16, int32, int64; 1-8
Unsigned uint, uint8, uint16, uint32, uint64, uintptr; 1-8
Unsigned byte byte = alias for uint8; 1
Unicode code point rune = alias for int32 4
Fractional numbers float32, float64; 4-8
Complex numbers complex64, complex128; 8-16

Note: The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.

Integers

Integer types come in signed and unsigned variants. Signed integers can represent negative numbers, while unsigned integers can only represent non-negative values.

package main

import (
	"fmt"
	"math/cmplx"
)

var (
	ToBe   bool       = false
	MaxInt uint64     = 1<<64 - 1
	z      complex128 = cmplx.Sqrt(-5 + 12i)
)

func main() {
	const f = "%T(%v)\n"
	fmt.Printf(f, ToBe, ToBe)
	fmt.Printf(f, MaxInt, MaxInt)
	fmt.Printf(f, z, z)
}

Floating Point Numbers

Go provides 32-bit and 64-bit floating-point types: float32 and float64. Use float64 for most purposes as it provides better precision.

Strings

A string is a sequence of characters enclosed in double quotes. Strings in Go are immutable.

Booleans

Variables declared without an explicit initial value are given their zero value.

The zero value is:

  • 0 for numeric types,
  • false for the boolean type, and
  • "" (the empty string) for strings.

Type Conversion

To convert between types, you use the syntax T(v) to convert value v to type T. Unlike C, Go assignment between items of different type requires an explicit conversion.

var i int = 42
var f float64 = float64(i)
var u uint = uint(f)