0
0
Goprogramming~5 mins

Type inference in Go

Choose your learning style9 modes available
Introduction
Type inference lets Go figure out the type of a variable automatically so you don't have to write it. This makes your code shorter and easier to read.
When you want to declare a variable without writing its type explicitly.
When the value assigned clearly shows what type the variable should be.
When you want to keep your code clean and simple.
When you are working with short variable declarations inside functions.
When you want to avoid repeating the type name.
Syntax
Go
variableName := value
The := operator declares and initializes a variable with inferred type.
This syntax can only be used inside functions, not at package level.
Examples
Go infers x is an int because 10 is an integer.
Go
x := 10
Go infers name is a string because of the quoted text.
Go
name := "Alice"
Go infers pi is a float64 because 3.14 is a decimal number.
Go
pi := 3.14
Go infers flag is a bool because true is a boolean value.
Go
flag := true
Sample Program
This program shows how Go automatically figures out the type of each variable using :=. It prints their values.
Go
package main

import "fmt"

func main() {
    age := 25
    city := "Paris"
    temperature := 18.5
    isRaining := false

    fmt.Println("Age:", age)
    fmt.Println("City:", city)
    fmt.Println("Temperature:", temperature)
    fmt.Println("Is it raining?:", isRaining)
}
OutputSuccess
Important Notes
You cannot use := outside functions; use var with explicit type there.
Type inference works only when you assign a value at the same time as declaring.
If you want to change the variable type later, you must declare a new variable.
Summary
Type inference lets Go guess the variable type from the value you give it.
Use := inside functions to declare and assign variables quickly.
It makes your code shorter and easier to read without losing type safety.