Variables and types

var and :=, the basic types, constants, zero values and converting between types with strconv.

Runs in Zerethon IDE · Go 1.27 Official Go documentation ↗

Go is statically typed. var x int = 3 declares a variable with a type; inside a function x := 3 declares it and infers the type. A variable that is declared but never set holds its type's zero value: 0, "", false or nil.

main.go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	var count int = 3
	price := 9.5
	name := "Ada"
	ready := true
	var nothing *int

	fmt.Printf("%T %T %T %T %v\n", count, price, name, ready, nothing == nil)
	n, err := strconv.Atoi("42")
	fmt.Println(n+1, err)
	fmt.Println(float64(count)*price, strconv.Itoa(7)+"7")
	fmt.Println(7/2, 7.0/2, 7%2)

	const limit = 10
	var empty string
	fmt.Printf("%d %q %d\n", limit, empty, len(name))
}

Output

int float64 string bool true
43 <nil>
28.5 77
3 3.5 1
10 "" 3
  • Go never converts between types for you: count * price with an int and a float64 does not compile — write float64(count) * price.
  • Integer division truncates: 7/2 is 3. Use floats for 3.5.
  • strconv.Atoi turns text into an int and returns an error as the second value; strconv.Itoa goes the other way.
  • A declared variable that is never used is a compile error (declared and not used).