Now, let’s talk about variables.
Variables can be declared with the keyword var
:
- Can be a list of variables: `var a, b, c int
- Can be used within functions (used at package or function level)
- A
var
declaration can have an initialisation:var i int = 1
Yet, var
can also be used without directly defining the data (initialization). A declaration alone looks like this:
Thinking back to the last section and the topic ofinference, a standalone declaration, as in the example, is the exception to the rule. In this case, we need to provide a data type, as Go can’t infer the type from the value (as we don’t provide a value).
Later in our code, an integer value can be assigned to our variable like this:
Aside from var
there is also :=
. This syntax can be used to declare and initialize variables within functions. It looks like this:
- Can be used instead of
var
only inside of functions - We don’t need to and can’t provide a data type
- Can’t be used at the package level
- Outside of functions, everything begins with a keyword
Constants
Constants are variables whose values can’t be changed. To make this clear, let’s first change the values of some variables.
By using =
we can assign a new value to a variable - no matter if it was created using var
or :=
:
Creating a constant using const
works the same as using var
- just exchange the keyword:
Now, the value of i
can’t be changed - it is constant.
To create constants, we need to use the const
keyword explicitly.