Learnmonkey Learnmonkey Logo

Go Variables

What are Variables?

Well, let's break down the word "variable". It sounds like the words "vary" and "able" chained together, right? So, the word variable means some thing that can be changed, or varied.

You can think of a variable as a box and the name of the variable as box's label. You can't change the label, but you can change what's inside the box.

Why use Variables?

You might think that variables are super useless, but they are one of the most important things in all of programming. Why?

Well, imagine you were programming a 2d game. When making games, you need to know the position of the player. But you can't know the position. The player decides that. So, you put the position in a variable. Instead of checking the player's position every single time you need to check for collision, etc, you can just access the variable you have instead of using a long function to get the position of the player.

Making Variables in Go

It's actually very easy to make variables in Go. Simply type var [variable name] to initialize an empty variable. If we want to initialize a variable and set it to a value, we type var [variable name] = [value].

When you first create a variable, you MUST use var or the short-declare operator (:=).
Once you make a variable, you HAVE to use it. If you don't, you'll get an error.

Go is statically-typed, which means that the type of variable (integer, string, boolean, etc.) cannot change. When you make a variable, Go infers the type. Below is some code that will cause an error:


var x = 3;
x = "Hello World!"
    

You could also make a new variable and give it a value without writing var by using a short-declare operator — := — instead of an equals sign. For example: var x = 3 is the same as x := 3. However, you cannot use := once you have already defined a variable to change its value. Use = for that.

Explicit Variable Data Types

In Go, everything is statically-typed, meaning if you assign the variable to something other than when the variable's data type was when declared, you'll get an error. When we do something like var x = 3, Go is implicitly inferring that the data type is integer. If we then try and do x = "some text", we get an error.

In Go, we can also declare our variable types explicitly. For example, instead of doing var x = 3, we can do var x int = 3. This can be very useful when we are debugging our code.