- Declare variables with
varand:=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
constandiota
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.
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)
}Leyla 15 Baku 4 3
var count int = 0
var ready bool = false
var title string = "Go course"var count int
var ready bool
title := "Go course"var count int is already 0. When you need a starting value inside a function, use :=.Basic types and zero values
| Type | Example | Zero value | Note |
|---|---|---|---|
int | 42, -7 | 0 | whole number; 64 bits on 64-bit systems |
float64 | 3.14 | 0 | decimal number |
string | "Baku" | "" | text, stored as UTF-8 bytes |
bool | true, false | false | logical value |
rune | 'ə' | 0 | one Unicode character (another name for int32) |
byte | 'A' | 0 | one 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.
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.
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')
}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.
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)
}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.
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))
}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.
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)
}Hello 12.56636 0 1 2
Key points
var x int = 5is the long form,x := 5is the short declaration inside functions;=only assigns to an existing variable.- A variable declared without a value gets its zero value:
0,"",falseornil. - Go does not convert types automatically: write
float64(a),int(x); integer division drops the fraction. strconv.Itoaandstrconv.Atoiconvert between numbers and strings;lencounts a string's bytes,utf8.RuneCountInStringits characters.constdeclares an unchangeable value;iotais a counter starting at 0 inside a constant group.
Check yourself
10 questions. Every correct answer earns XP.
var score int, what is the value of score?