Golang: Basic Types

By Xah Lee. Date: . Last updated: .

Basic Types

Go's basic types are

The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems.

Find a Value's Type

reflect.TypeOf(v) → returns the type of v. This is from the package "reflect"

package main

import "fmt"
import "reflect"

func main() {

        var nn = 3
        var ff = 3.123

        // find the type of a value
        fmt.Println(reflect.TypeOf(nn)) // int
        fmt.Println(reflect.TypeOf(ff)) // float64
}

Type conversions

type(v) → converts the value v to the type type, where type is the same keyword as the type declaration, e.g. int, string, bool, etc.

package main

import (
        "fmt"
        "reflect"
)

func main() {
        var i int = 42
        var f = float64(i)
        fmt.Println(reflect.TypeOf(f)) // float64
}

Type inference

When declaring a variable without specifying an explicit type , the variable's type is inferred from the value on the right hand side.

package main

import "fmt"
import "reflect"

func main() {

        var i int

        // type of j is inferred from i
        var j = i

        fmt.Println(reflect.TypeOf(j)) // int
}

When the right hand side is a number, the new variable may be an int, float64, or complex128 depending on the precision of the number.

package main

import "fmt"
import "reflect"

func main() {

        var i = 42       // int
        var f = 3.142    // float64
        var g = 1 + 0.5i // complex128

        fmt.Println(reflect.TypeOf(i)) // int
        fmt.Println(reflect.TypeOf(f)) // float64
        fmt.Println(reflect.TypeOf(g)) // complex128
}

Reference

The Go Programming Language Specification - The Go Programming Language#Types