Skip to content
Educora
Beginner14 min2 / 10

Variables, types and constants

Declare variables with `var` and `:=`, and learn the basic types, zero values, conversions, strings and constants with `iota`.

Check yourself
In this lesson you will learn
  • Declare variables with var and := and explain the difference
  • Recognise the basic types and their zero values
  • Convert types explicitly and convert between strings and numbers with strconv
  • Create constants with const and iota

Imagine you are writing a game. Where do you keep the player's name, score, level and whether they are online? In variables. In Go every variable has an exact type, and the compiler will not let you store a value that does not fit it. In this lesson you will learn to declare variables and constants, meet the basic types and convert between them.

Declaring variables

Go has two ways to declare a variable. The long form uses the var keyword: var age int = 14. If you give a value, you may leave out the type — Go works it out. Inside functions the short declaration is used most often: city := "Baku". := creates a new variable, while a plain = gives a new value to a variable that already exists.

Go
package main

import "fmt"

func main() {
	var name string = "Leyla"
	var age = 14
	city := "Baku"
	x, y := 3, 4
	age = age + 1
	x, y = y, x
	fmt.Println(name, age, city)
	fmt.Println(x, y)
}
Expected output
Leyla 15 Baku
4 3
Too wordy
var count int = 0
var ready bool = false
var title string = "Go course"
Idiomatic Go
var count int
var ready bool
title := "Go course"
If the zero value is what you want, don't write it — var count int is already 0. When you need a starting value inside a function, use :=.

Basic types and zero values

TypeExampleZero valueNote
int42, -70whole number; 64 bits on 64-bit systems
float643.140decimal number
string"Baku"""text, stored as UTF-8 bytes
booltrue, falsefalselogical value
rune'ə'0one Unicode character (another name for int32)
byte'A'0one byte (another name for uint8)

There are also types with an explicit size: int8, int16, int32, int64, the unsigned uint, uint8… and float32. In everyday code int, float64, string and bool are usually enough.

Definition
Zero value

The value a variable gets automatically when it is declared without one: 0 for numbers, the empty string "" for strings, false for bool, and nil for pointers, slices and maps. In Go no variable ever holds random garbage.

Go
package main

import "fmt"

func main() {
	var n int
	var f float64
	var s string
	var ok bool
	fmt.Println(n, f, ok)
	fmt.Printf("%q\n", s)
	fmt.Printf("%T %T %T %T\n", 42, 2.5, "hi", 'A')
}
Expected output
0 0 false
""
int float64 string int32

%q prints a string inside quotes, so an empty string becomes visible. Notice that 'A' in single quotes is not a string but a rune, the Unicode number of a character. That is why its type prints as int32. A decimal literal without a type (2.5) always becomes a float64.

Conversions and arithmetic

Go never converts types behind your back: you cannot add an int and a float64 directly. Conversions are written explicitly: float64(a), int(x). Dividing two integers gives an integer — the fractional part is dropped — and % gives the remainder. For converting between strings and numbers there is the strconv package: Itoa turns a number into a string, and Atoi turns a string into a number.

Go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	a, b := 7, 2
	fmt.Println(a/b, a%b)
	fmt.Println(float64(a) / float64(b))
	price := 2.5
	fmt.Println(price * float64(a))
	s := strconv.Itoa(a) + " apples"
	fmt.Println(s)
	n, err := strconv.Atoi("42")
	fmt.Println(n+1, err)
}
Expected output
3 1
3.5
17.5
7 apples
43 <nil>

Atoi returns two values: the number and an error. When the conversion succeeds, the error is nil, and Println prints it as <nil>. You will learn error handling in detail in a later lesson.

Strings and characters

In Go a string is an immutable sequence of bytes, and text is stored in UTF-8. Latin letters take one byte, while letters such as ə, ş and ı take two. That is why len returns the number of bytes, not characters. To count characters, use RuneCountInString from the unicode/utf8 package. The strings package has many ready-made tools: ToUpper, Contains, Replace, Split, TrimSpace and more.

Go
package main

import (
	"fmt"
	"strings"
	"unicode/utf8"
)

func main() {
	city := "Gəncə"
	fmt.Println(len(city), utf8.RuneCountInString(city))
	fmt.Println(strings.ToUpper(city), strings.Contains(city, "ncə"))
	msg := "Welcome to " + city + "!"
	fmt.Println(msg)
	fmt.Println(strings.Replace(msg, "Welcome to", "Hello from", 1))
	fmt.Println(strings.Repeat("=", 10))
}
Expected output
7 5
GƏNCƏ true
Welcome to Gəncə!
Hello from Gəncə!
==========

Constants and iota

A constant is declared with const and cannot change while the program runs. Constants are computed at compile time, so their value must be something simple such as a number, a string or a bool. Inside a group of constants in parentheses, iota is a counter that starts at 0 and grows by 1 on each line. It is handy for lists such as sizes, days of the week or statuses.

Go
package main

import "fmt"

const Pi = 3.14159

const (
	Small = iota
	Medium
	Large
)

func main() {
	const greeting = "Hello"
	r := 2.0
	fmt.Println(greeting, Pi*r*r)
	fmt.Println(Small, Medium, Large)
}
Expected output
Hello 12.56636
0 1 2

Key points

  • var x int = 5 is the long form, x := 5 is the short declaration inside functions; = only assigns to an existing variable.
  • A variable declared without a value gets its zero value: 0, "", false or nil.
  • Go does not convert types automatically: write float64(a), int(x); integer division drops the fraction.
  • strconv.Itoa and strconv.Atoi convert between numbers and strings; len counts a string's bytes, utf8.RuneCountInString its characters.
  • const declares an unchangeable value; iota is a counter starting at 0 inside a constant group.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
After var score int, what is the value of score?