Lesson 2 · 2 of 20
Variables and types · Go
Store data in Go variables with var and :=, meet the basic types (int, float64, string and bool) and the zero value of each one.

A variable is a name for a piece of data. var declares one with its type: var city string = "Valencia" creates a string and var population int = 800000 a whole number. In Go the type goes after the name.
The short form := declares the variable and works out the type from the value: temperature := 21.5 is a float64 (a number with decimals) and isCoastal := true is a bool (true or false). It only works inside a function, and it is the form you will see most.
A variable declared without a value gets its zero value: 0 for numbers, "" (empty string) for string and false for bool. That is why visitors is 0 and note comes out empty between the brackets.
%T inside fmt.Printf prints the type of each value; lesson 4 covers the rest of these verbs. At the end, = (without the colon) gives an existing variable a new value, always of the same type, and visitors += 1500 adds 1500 to it.
Go does not let you declare a variable and leave it unused: the program would not compile. It is one of the rules the language uses to keep code tidy.
Code · main.go
package mainimport "fmt"func main() { // var declares a variable with its type. var city string = "Valencia" var population int = 800000 // := declares it and takes the type from the value. temperature := 21.5 isCoastal := true // Without a value, a variable starts at its zero value. var visitors int var note string fmt.Println("City:", city) fmt.Println("Population:", population) fmt.Println("Temperature:", temperature) fmt.Println("Coastal:", isCoastal) fmt.Println("Visitors:", visitors, "Note: ["+note+"]") // %T prints the type of each value. fmt.Printf("Types: %T %T %T %T\n", city, population, temperature, isCoastal) // = gives a new value of the same type. population = 810000 visitors += 1500 fmt.Println("Now:", population, "people and", visitors, "visitors")}Output · go run main.go
City: Valencia Population: 800000 Temperature: 21.5 Coastal: true Visitors: 0 Note: [] Types: string int float64 bool Now: 810000 people and 1500 visitors
Key points
var name type = valuedeclares with the type in sight.name := valuedeclares and infers the type.- Basic types:
int,float64,stringandbool. - Without a value, every variable starts at its zero value.
:=creates the variable;=changes its value.
Exercise
Add country := "Spain" and area := 134.6 (the area in km²), print them with Println and check with %T which type Go inferred for each one.