CodeNebula
Go🔧Core Languagebeginner

Variables and Type Inference

Go · Core Language · Run with go run

Explanation

Go is statically typed but uses type inference to eliminate boilerplate. The `:=` short declaration infers the type from the right-hand side at compile time. `var` declarations with explicit types are used at package level or when the zero value is intentional.

Real-World Scenario

In a web handler parsing a JSON body, you write `data := make(map[string]any)` rather than `var data map[string]interface{}` — same safety, less noise.

Quick Snippet

snippet.go
package main

import "fmt"

func main() {
    x := 42            // int inferred
    name := "Go"       // string inferred
    ratio := 3.14      // float64 inferred
    active := true     // bool inferred

    var count int      // zero value: 0
    var label string   // zero value: ""

    fmt.Println(x, name, ratio, active, count, label)
}

Full Example

variables.go
// Compile: go run variables.go
// Output:
//   42 Go 3.14 true 0
package main

import "fmt"

func main() {
	x := 42
	name := "Go"
	ratio := 3.14
	active := true

	var count int    // zero value: 0
	var label string // zero value: ""

	fmt.Println(x, name, ratio, active, count)
	_ = label
}
Run command
go run variables.go