A Glimpse into Variables in Go

A Glimpse into Variables

Are you as excited as I am to advance to the next part of our learning journey? The topic of this lesson is variables — a core concept that you will use constantly in your programming career.

Meet the Variables

In programming, a variable is akin to a container for storing information. Various types of information — such as words, numbers, and more — can be stored in this container. Here is an example of how to create a variable in Go:

package main

import "fmt"

func main() {
    var destination string
    destination = "Paris"
    fmt.Println(destination)
}
// Output: Paris

We've created a variable named destination. This process is known as declaring a variable. When declaring, we choose a fitting name for the container of information, followed by the type of data we expect to store. In Go, we declare a variable using the var keyword, followed by the variable name and finally its type. Following the declaration, we stored the string "Paris" in it. We assign a value to a variable with the assignment operator =. The variable that should store the value is on the left, while to acutal value is to the right.

This way of declaring a variable first and then assigning the value can get cumbersome after a while. Alternatively, we can use the shorthand operator := to both declare and initialize the variable, which allows Go to infer the type:

package main

import "fmt"

func main() {
    destination := "Paris"
    fmt.Println(destination)
}
// Output: Paris

Using this syntax, we forgo both the var keyword as well as the type declaration. The Go compiler is smart enough to know that if you are assigning a value within double quotes to a variable, the type should be a string. In Go, the term string refers to a sequence of characters. Any text no matter the lenght is considered a string as long as it is surrounded by double quotes.

Be careful! This shorthand only works within functions (in our example, we are writing code in the main function). If you are declaring variables out of a function, you need to use the full syntax, with the caveat that the value can be assigned at declaration time:

package main

import "fmt"

var destination string = "Paris"

func main() {
    fmt.Println(destination)
}
// Output: Paris

For now we will only use variables within functions, but it is good to keep this detail in mind if you get stuck declaring variables outside of functions.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal