Gaaker Go

Golang Type inference

When declaring a variable without specifying its type, the type of the variable is deduced from the right side.

When the type is declared on the right side value, the type of the new variable is the same as it:

var i int
j := i // j is an int too

However, when the right side contains an unspecified numeric constant, the type of the new variable may be int, float64 or complex128, depending on the precision of the constant:

i := 42           // int
f := 3.142        // float64
g := 0.867 + 0.5i // complex128

The following is a complete code example.

package main

import "fmt"

func main() {
	v := 1
	fmt.Printf("v is of type %T\n", v)

    v1 := 1.1
	fmt.Printf("v1 is of type %T\n", v1)

    v2 := "golang"
    fmt.Printf("v2 is of type %T\n", v2)

Below is the program output:

v is of type int
v1 is of type float64
v2 is of type string
< Type inference Type inference >