Learning variables in GO

Variables in Go, What is a Variable?

 

So before we talk about variables in Go specifically let’s make sure that we understand what a variable is. A variable has two parts, a name, and a location in the computer’s memory that holds a value. In programming, you can think of a variable like a P.O. box at the post office.

The P.O. box has an address, the P.O. box number that the postal service uses to know when you send mail which physical box you want the mail to be delivered to. In your code the name of your variable is like the P.O. box address, it’s how you refer to the box so that your program knows which variable to look up.

The memory location is like the physical P.O. box that the address points to. We can store something in the P.O. box, we can take things out of the P.O. box, and we can put new things in the P.O. box. But the P.O. box itself is still the same physical box, we’re just changing what’s currently stored in it.

Getting Set Up

If you’ve chosen to use VS Code as your IDE to follow along in this blog I just wanted to take a moment to explain how I’ve got my IDE set up for this post. If you’re not using VS Code or already have it configured feel free to skip straight to Using Variables in Go.

When you first open VS Code you’ll be presented with the Welcome Screen. Click on the Open folder option under Start to create the space for our new variables in Go project.Create your Variables in Go project Navigate to the src folder in your GOPATH and create a new folder, I named mine variables. Select the new folder icon on your variables project in the explorer and first create a main folder and then create a main.go file in that folder. Open the main.go file in the editor. We’ll use this file for all of the code in our variables in Go project.variables in go project structure One final optional step that I set up on my IDE is enabling autosave. You don’t need to turn on autosave, but I find it incredibly convenient. If you don’t choose to enable autosave you’ll need to explicitly save your code each time you want to run it.

Using Variables in Go

Let’s start off using our code from the “Hello World” program we wrote when we installed Go (Mac or Windows) on our computer.

1
2
3
4
5
6
7
8
9
package main

import (
"fmt"
)

func main() {
fmt.Println("Hello, world!")
}

In our terminal panel let’s run the following command real quick to run our program and remind us what it does.

Enable terminal pane in VS Code

1
go run main/main.go

In this program, we tell the computer to print out the exact words “Hello, world!”. Pretty cool that we made the computer do something we told it to, but kind of limited in what else it lets us do. What if we wanted to make the computer say “Hello, world!” multiple times? We would have to type out the whole sentence every time. What would be more useful is if we assigned the sentence to a variable and then made our program print that variable.

1
2
3
4
5
6
7
8
9
10
11
12
package main

import (
"fmt"
)

func main() {
var hello = "Hello, world!"
fmt.Println(hello)
fmt.Println(hello)
fmt.Println(hello)
}

Now we’re getting somewhere! We’re not really leveraging the full power of variables yet though. Remember, a variable refers to a location, and we can change the value that we’re storing in that location. So let’s update our program to be a little more interesting and run it again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import (
"fmt"
)

func main() {
var hello = "Hello, world!"
fmt.Println(hello)
hello = "Hello, Learn Coding With GO!"
fmt.Println(hello)
hello = hello + " I'm a Go program :)"
fmt.Println(hello)
}

So, now we have our variable “hello” that has the value of “Hello, world!”, and because a variable’s value can be changed we’ve set the value of hello to “Hello, Learn Coding With Go!” after the first time we print it. This is new for us, but not surprising. The next thing we do with our “hello” variable though is where we start to really reveal the power of variables in Go. We don’t just have to set our variable to a specific value that we wrote in our code (often referred to as “hard coding”) we can have our program change the value of our variable based on the result of an expression. In this case, we’re setting the value of the variable “hello” to equal the combination of its current value and the sentence ” I’m a Go program!”. We can use the current value of “hello” in our expression because the expression on the right side of the “=” sign is evaluated first. So we’re not setting the new value of “hello” until after we’ve added the current value and our new sentence together.

In Go (and most programming languages) our sentence “Hello, world!” is referred to as a string. A string, are you’re probably guessing (though not in these words) is a sequence of characters. There’s actually an important reason for that odd wording, a string doesn’t have to just be made up of letters, a string can include punctuation like our exclamation point and comma, as well as whitespace (the space after the comma before “world”), and even numbers. Strings can also include special characters, like “\n” which tells the computer to put whatever comes after the “\n” on a new line. Let’s try that real quick so you can see it in action for yourself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
"fmt"
)

func main() {
var hello = "Hello, world!"
fmt.Println(hello)
hello = "Hello, Learn Coding With GO!"
fmt.Println(hello)
hello = hello + "\nI'm a Go program :)"
hello = hello + "\n10"
fmt.Println(hello)
}

Types and Variables in Go

No discussion of variables in Go would be complete without mentioning types. Programming languages are divided into two groups, statically typed languages and dynamically typed languages. Go is a statically typed language, this means that every variable has a type and you can only store values of that type in the variable. Once the variable is created it’s type is set and cannot be changed.

It’s a common misconception that dynamically typed languages don’t have types at all. This isn’t true, instead, the difference is that in a dynamically typed language the type is associated with the value, not the variable. So in a dynamically typed language, a variable can hold a value of any type. This means that you can create a variable and store a number in it, then later store a string in it.

While it seems convenient to be able to store any value in a variable without needing to assign a type to the variable this can lead to mistakes when you write your program that causes it to crash (fail) or even worse look like it’s working but does things you didn’t expect it to do. Say that you have a program that is doing some math and you have a variable that you’re setting based on input from a user. You’re using that variable in the math of your program. If a user provides a number like you expect then everything works just fine.

Now all of a sudden the user provided a string instead of a number. In a statically typed language, you cannot assign a string to a number type variable. However in a dynamically typed language, it’s possible, and if you don’t check to make sure that what the user provided was actually a number your code might not care. The numerical representation of the string “ten” is 116 101 110 and it’s possible your code may simply perform the math you asked it to use those numbers when you and your user expected it to use 10.

Inferred Types

Now, you may have noticed that I said that Go was statically typed, but in our examples thus far we didn’t tell Go the type of our variable. That’s because when we first created our “hello” variable we assigned a value to it in the same step.

1
var hello = "Hello, world!"

Because of this Go was able to infer that the type of “hello” must be a string because we assigned a string to it. Go has another shortcut when creating a variable and assigning to it at the same time. We can skip the “var” keyword completely in this case by using “:=” instead of “=”. This is shorthand in Go for “I want to assign to a variable and I want Go to create it if it doesn’t already exist. In Go you can assign to multiple variables at the same time. When using the “:=” shortcut at least one of the variables you’re assigning to has to be new. Go will throw an error if you use “:=” to assign to a variable that already exists.

1
2
3
hello, world := "Hello", "World"
world = "Learn Coding With Go"
hello = "Hey"

Go can only infer the type of a variable if you’re assigning a value to it at the same time that you’re creating it. If you want to create a variable before you actually use it, then you need to explicitly tell Go what the type of that variable is and use the “var” keyword. The format is var

1
2
3
4
5
6
7
8
9
10
11
12
package main

import (
"fmt"
)

func main() {
var hello string
hello = "Hello, world!"

fmt.Println(hello)
}

Variables in Go have many types, and you can even create your own types. We’ll start off by only using a few of these types in our early programs though. For a quick introduction, I’ve listed them here.

TypeNameDescription
stringStringA sequence of characters
intIntegerA whole number with no decimals
floatFloatA number with a decimal component
BoolBooleanA true or false value
Chris Sotherden

Originally a native of upstate NY, I relocated to North Carolina in 2013 where I've since helped open the new R&D headquarters for Optanix. I've been with Optanix (formerly ShoreGroup) for over ten years, where I've worked my way up from entry-level to Lead Architect. I taught myself programming in high school and am an all around technology nerd from the design of programming languages and compilers, to quantum computing, and rockets. Outside of technology I've competed in powerlifting and medium distance running, as well as smoking some mean BBQ. Oh, my partner and I also breed, show, and sell fancy goldfish!

>