Theory

Declaring & assigning

Last lesson you wrote your fields on paper — today they become real variables. A variable is a named place for a value: a labelled box the program puts data into and takes data out of.

Go gives you three ways to create one:

  • Full formvar title string = "Dune". Everything spelled out: the word var, a name, a type, a value. Use it when you want the type in black and white, or when declaring without a value.
  • Short formpages := 380. Go infers the type from the value (380int). This is the default form inside functions — you will see it the most.
  • Constantconst appName = "Book list". A value that never changes while the program runs. Assigning to it again does not even compile.

When to pick which:

Situation Form
A normal variable inside a function :=
Declare now, assign later var
Fixed for the program's lifetime const

Tip. := only works inside functions. At file level (next to import) only var and const are allowed — you will see this in the very next step.