Skip to main content
eLearner.app
Module 1 · Lesson 1 of 51/50 in the course~10 min
Module lessons (1/5)

Variables and types

In Go every variable has a static type known to the compiler: once declared, a variable cannot change type. This rigidity — very different from JavaScript or Python — is the price you pay to get compile-time errors instead of runtime ones, small binaries, and predictable performance.

Two forms of declaration

var with explicit type

Go
var name string = "Ada"
var age int = 36
var active bool

When you omit the value (as in var active bool) the variable receives the zero value of its type — we'll come back to this in the next lesson.

Short declaration :=

Inside a function you can use :=, which infers the type from the expression on the right. It is the idiomatic form and the one you'll use 90% of the time:

Go
name := "Ada"   // string
age := 36        // int
pi := 3.14       // float64
active := true   // bool

The basic types you'll meet right away

TypeExampleNotes
int42size depends on the CPU (32 or 64 bit)
float643.14default for decimal literals
string"Ada"UTF-8, immutable
booltrue, falseno "truthy", only pure bool
rune'A'alias of int32, represents a Unicode code point
byte0x7Falias of uint8

There are also int8/16/32/64, uint8/16/32/64, float32 and complex64/128 for when you need precise sizes (binary parsing, interop, etc.).

Multiple declarations

You can declare several variables with a var-block or a plural :=:

Go
var (
    name   string = "Ada"
    age    int    = 36
    active bool
)

x, y := 10, 20
a, b, c := "a", 2, true   // different types: no problem

Variables declared but not used

Go is strict: a variable declared and never used is a compilation error, not a warning. The same applies to unused imports.

Go
func main() {
    x := 42
    // error: x declared and not used
}

To silence the rule temporarily you use _ (blank identifier):

Go
_ = x

Your turn

Exercise#go.m1.l1.e1
Attempts: 0Loading…

Use var to declare a variable name of type string with value 'Ada' and print it.

Loading editor…
Show hint

The long form is `var <name> <type> = <value>`.

Solution available after 3 attempts

Exercise#go.m1.l1.e2
Attempts: 0Loading…

On a single line, use := to assign 36 to age and 'Roma' to city, then print both.

Loading editor…
Show hint

You can assign multiple variables at once: `a, b := 1, "due"`.

Solution available after 3 attempts

Quiz#go.m1.l1.e3
Ready

Which of these declarations produces a compilation error if placed OUTSIDE a function?

Go
// (a)
var name string = "Ada"

// (b)
age := 36

// (c)
const PI = 3.14
Answer options

Recap

  • Static type, automatically inferred by := or declared with var.
  • := only inside functions; at package level only var/const.
  • Unused variables and imports = compilation error: use _ to silence them.
  • int/float64/string/bool cover 90% of everyday cases.