Declaring variables can be done using the
var keyword or using the short declaration symbol
var statements can be at both package or function levels.
Short declarations with
:= is only available at the function level.
:= uses implicit type declaration, i.e. it infers the type of the variable from the declaration. This is known as type inference.
We can initialise multiple variables on the same line.
uintptrtypes are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems.
When we declare a variable without an initial value, it takes on a default zero value.
Zero value for types:
In Go, we need to explicitly convert between types. Implicitly converting
float or vice versa is not allowed.
To make a variable or as we will see later for methods, we name it starting with a capital letter, e.g.
Ball. Variables starting with a lowercase alphabet is not exported, and hence, will be not be accessible outside the package, e.g.
We can also omit the
a, b in the return statement of
namedReturn function. This is known as a naked return. However, this is only recommended for short functions so as to maintain code readbility.
Exercise: Swap 2 Variables
In Go, we can swap the values stored in two variables in just one line as shown above (similar to Python).
Constants can be declared with the
:= is only used for variables. You cannot use it for constants.