Working with Variables in Go

10.19.2021

Intro

Declaring variables is a fundamental task in all programming languages. To do this in Go, we can use the following formula:

var [name of variables] [optional data type];

var is a reserved keyword that tells go we are going to declare a variable. We can then provide the name of a variable followed by an optional data type.

In this article, we will learn how to declare variables in Go.

Setting Up

Let's start be creating a new file

touch main.go

We can then add the following code.

package main

import "fmt"

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

We can run the code using the following.

go run main.go

Example of Statically Type Variables

Our first option to declare variables is using static typing. In this example, we use the var keyword, the name, and the type. By default, all values are set to nil or the "zero" value. In this case, the zero value of a string is an empty string.

package main

import "fmt"

func main() {
    var name string
    fmt.Println(name)
}

The data type used here is string. You can find a list of supported data types by Go here: https://tour.golang.org/basics/11.

Once, we declare a variable, we can then initialize (or assign) the variable to have a value.

package main

import "fmt"

func main() {
    var name string
    name = "Keith"
    fmt.Println(name)
}

We can also combine this into one line.

package main

import "fmt"

func main() {
    var name string = "Keith"
    fmt.Println(name)
}

Another option, is to declare multiple variables at the same time. We do this by using the same format, but adding a comma between variable names and with the values.

package main

import "fmt"

func main() {
    var x, y int = 20, 30
    fmt.Println(x, y)
}

Example of Dynamic Type Variables

Go allows us to dynamically type variables, which means we can drop the type declaration and Go will infer it. Here is an example declaring our numbers which Go will infer the type from.

package main

import "fmt"

func main() {
    var x, y = 20, 30
    fmt.Println(x, y)
}

If we want, we can also drop the var keyword and use the := walrus operator.

package main

import "fmt"

func main() {
    a, b := 50, 80
    fmt.Println(a, b)
}