Variables & Data Types

Go is statically typed: every variable has a fixed type, decided either by you or by the compiler, and that type never changes for the life of the variable.

Declaring with var, and the := shorthand

var declares a variable with an explicit type. Inside a function, the shorter := form is more common — it declares the variable and infers its type from the value on the right in one step:

Go main.go
package main

import "fmt"

func main() {
	var name string = "Priya"
	age := 29

	fmt.Println(name, age)
}
Output
Priya 29

var name string = "Priya" spells out the type explicitly. age := 29 does the same job with less typing — Go looks at 29, decides it's an int, and gives age that type permanently. := only works for a brand-new variable inside a function; package-level variables must use var.

Basic types

Go's everyday types include int, float64, string, and bool:

Go main.go
package main

import "fmt"

func main() {
	count := 12
	price := 4.5
	name := "widget"
	inStock := true

	fmt.Println(count, price, name, inStock)
}
Output
12 4.5 widget true

int holds whole numbers, float64 holds decimals (and is the default Go picks for any number literal with a decimal point), string holds text, and bool holds true/false. Once count is inferred as int, trying to assign a string to it later is a compile error, not a runtime surprise.

Zero values

A variable declared with var and no initial value isn't left undefined — Go gives it a sensible default called the zero value, based on its type:

Go main.go
package main

import "fmt"

func main() {
	var count int
	var price float64
	var name string
	var ready bool

	fmt.Println(count, price, name, ready)
}
Output
0 0  false
Note: the zero value for int is 0, for float64 is 0, for string is "" (an empty string — which is why it prints as nothing between the two spaces above), and for bool is false. This means a freshly declared Go variable is always in a valid, predictable state, unlike C, where an uninitialized local variable holds whatever garbage bits happened to be in that memory already.