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 form —
var title string = "Dune". Everything spelled out: the wordvar, a name, a type, a value. Use it when you want the type in black and white, or when declaring without a value. - Short form —
pages := 380. Go infers the type from the value (380→int). This is the default form inside functions — you will see it the most. - Constant —
const 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 toimport) onlyvarandconstare allowed — you will see this in the very next step.