Golang comes with a decent offering around variables that you can use to store, retrieve and manipulate information.
A variable is defined with the
var keyword followed by the name of the variable, the type and then the assignment itself.
How to name a variable in Golang
Variable names must:
- Start with a letter
- May contain letters, numbers or the underscore
Variable names that start with numbers or special characters are not allowed.
Number variable types
Let’s take a simple number, or integer as we often call it:
This declared a number, which we aptly call
aNumber, declare it as a type
Integer and then assign the value
13 to it.
Golang provides us with the ability to not have to type-cast variables all the time, by using the
:= assignment operator.
So taking the above example, let’s change it to use this new operator:
That was easy! What about other variable types you may ask… well, you can do it for everything!
Golang will also infer the type of initialised variables if we don’t specify them:
Numbers also come with additional sizes.
For Integer sizes, we have:
For Unsigned Integer sizes, we have:
Additional number variable types
Additionally to our standard Integer types, there also exists:
byte which is simply an alias for
rune which is an alias for
int32 and represents a Unicode code point
Then we have
float64 to store floating-point or decimal numbers.
As well as
complex128 for working with complex numbers as a whole.
String variable types
string type creates a standard variable string.
Boolean variable types
Booleans in Golang are either
We can set a Boolean to
true by declaring similarly to how we did for a
Scope of a variable
As with all other languages, variables have a scope.
This means that a variable can be accessed within the same scope that it is created in.
If you need to use a variable outside that creation scope, you will either need to pass it along when calling a function or method, or reference it using pointers.
Pointers tends to make things quite a bit more complicated if you are not ready for the concept yet.
Pointers allow for variables to not have to be redeclared and therefore allows for smaller application execution space.
We will cover this in greater detail in a future tutorial.
Constants are simply variables that cannot, or should not, be changed after they have been initialised.
In software engineering, this is called an
immutable type, as it is not able to change.
It is possible to declare multiple variables at once:
As you can see, it’s even possible to mix variable types during the automatic type cast assignment.
These common variables are at the core of what is required when creating applications in Golang.
Learn them and their usage to better understand how to create stable applications.