All About Variables & Constants
#
VariablesDeclaring 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.
#
Initialising VariablesWe can initialise multiple variables on the same line.
#
Basic Types in GoThe
int
,uint
, anduintptr
types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems.
https://tour.golang.org/basics/11
#
Zero ValuesWhen we declare a variable without an initial value, it takes on a default zero value.
Zero value for types:
int
takes0
boolean
takesfalse
string
takes""
#
Type ConversionsIn Go, we need to explicitly convert between types. Implicitly converting int
to float
or vice versa is not allowed.
#
Exported NamesTo 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. oranges
.
#
Named Return ValuesWe 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).
#
ConstantsConstants can be declared with the const
keyword.
Note: :=
is only used for variables. You cannot use it for constants.