GoGoPrimer
< Back to module

Basic syntax

Variables and types

Go offers two ways to declare a variable. The explicit form with `var`, which specifies the type, and the short form `:=`, which lets the compiler infer the type from the assigned value.

var name string = "Riadh"
var age int = 41
 
// équivalent, plus idiomatique à l'intérieur d'une fonction
name := "Riadh"
age := 41

`:=` only works inside a function, to declare AND initialize at the same time. At package level (outside a function), only the `var` form is allowed.

The basic types: `int` (signed integer, platform-dependent size, 64-bit in practice), `float64` (floating-point number), `string` (immutable UTF-8 string), `bool` (`true` or `false`). There are also explicit-size variants (`int32`, `int64`, `uint8`...) useful when memory size matters.

A variable declared without an initial value automatically gets the zero value for its type: `0` for numbers, `""` for strings, `false` for booleans. There is no such thing as an uninitialized variable in Go, unlike C.

var count int // 0
var label string // ""
var ready bool // false

Your turn

Declare three variables with `:=`: `city` (a city, string), `population` (an integer), `isCapital` (a boolean). Print them with `fmt.Println`.

package main
 
import "fmt"
 
func main() {
// tes déclarations ici
}