Golang Cheatsheet: Variables

March 31, 2019

Go or Golang is a fairly simple but extremely powerful programming language. In this post, we are going to become pros at working with variables and constants in Go.

Variables: Building Blocks

Variables are one of the most essential building blocks of any programming language and this is no different in Go. Variables in Go are easy to pickup and master because there are only a few rules and constraints to worry about.

The biggest one is perhaps the statically typed nature of the language. Developers familiar with typed languages like C# or Java will feel right at home, while those coming from dynamically typed languages like JavaScript may need to make a few adjustments. While Go is a statically typed language, it does introduce a certain degree of flexibility that I think becomes a key benefit as we’ll see in this article.

Cheatsheet TL;DR

If you already know all the nuances of working with variables in Go, but just need a quick refresher, then this section is for you. Here I won’t go into any in-depth explanations, instead I’ll just show you the different ways of working with variables and constants in Go. The goal for this section is to be a quick reference guide.

package main

// Declare variable without setting value
var message string
// Set value 
message = "Hello World"

// Declare variable and set value
var message string = "Hello World"

// Declare multiple variables of the same type
var firstName, middleName, lastName string

// Declare and set value for multiple variables of the same type
var firstName, middleName, lastName string = "John", "Fitzgerald", "Kennedy"

// Alternative way to declare multiple variables
var (
  firstName string
  middleName string
  lastName string
)

// Alternative way to declare and set multiple variables
var (
  firstName = "John"
  middleName = "Fitzgerald"
  lastName = "Kennedy"
)

// Declare multiple strings of different types
var (
  firstName string
  middleName string
  age int
)

// Declare and set multiple variables of different types
var (
  firstName = "Ado"
  middleName = "Kukic"
  age = 29
)

// Declare and set a value for a constant
const pi float32 = 3.14

func main(){

  // All of the above can be used inside or outside of a function

  // All of the below only works inside of a function

  // Shorthand variable declaration
  name := "Ado Kukic"

  // Shorthand multiple variable declaration of same type
  firstName, lastName := "Ado", "Kukic"

  // Shorthand multiple variable declaration of different types
  firstName, lastName, age := "Ado", "Kukic", 29

  // Declare a const and let Go infer the type
  const answerToLife = 42

  // Discard value
  firstName, _ := user()
  // user() function returns two values
  // The first value is set to firstName variable
  // The second value is discarded

  // Variable redeclaration

  // Declare a variable err
  err := false

  // Declare a variable success, and redeclare the err variable
  // Redeclaration can only be done if shorthand notation is used and
  // at least one new variable is introduced
  success, err := false, true

}

Golang Variables In-Depth

If you are new to Go and want to learn all the ways to work with variables, then you’ve come to the right place. Throughout the next few sections we’ll cover all the intricacies, nuances, and rules for working with variables and constants in Go. Let’s dive right in.

My First Variable In Go

Variables in Go are created with the var keyword followed by the name of the variable. There are other ways to create variables, but we’re starting with the basics. Let’s create and print out our first variable in the Go programming language.

// Every Go program must have a main package
package main

// The "fmt" library exposes a number of useful methods for displaying content in our terminal window
import "fmt"

// The "main" function is executed by default when you run your Go program
func main(){

  // Declare a variable called "hello" and set its value to "Hello World"
  // Since the value we are setting is a string, the "hello" variable will be of type string
  var hello = "Hello World"
  
  // Print the value of "hello" to our terminal window
  fmt.Println(hello) // "Hello World"
}

Every example I show will be a fully functional Go program, so to reinforce your learning and get the most out of this article I suggest you either run it locally or on the Go Playground.

Type Inference in Go

Go is a typed programming language. Each variable you declare must have a type associated with it. If you do not explicitly assign a type to a variable in your program, Go will do it for you.

Go has a number of primitive types you would expect such as string, bool, int, and others. Deeper explanation of individual types is out of scope for this article, but I will create a cheatsheet for that as well in the future. Let’s see how we can explicitly declare a type for our variables in Go.

package main

import "fmt"

func main() {

  // Declare a variable and explicitly set it to a type of string
  var name string = "Ado"

  // Declare a variable of type int
  // Since we declared a type we don't have to automatically assign a value to it
  var age int 
  
  // Assign a value of 29 to the age variable
  // We can do this because our Go program knows that the age variable is of type int
  age = 29

  fmt.Println(name, age) // Ado 29

}

To explicitly set a type for your variables in Go, you simply declare the type after the variable name. If you create a variable with an explicit type and then try to set its value to something not of that type, your program will not compile. Let’s see an example of that.

package main

import "fmt"

func main() {

  // Error: cannot use 21 (type int) as type string in assignment
  var city string = 21

  fmt.Println(city)
}

If you try to run the above code you will get the following error: cannot use 21 (type int) as type string in assignment because the number 21 is of type int, while the string city is expecting a string value.

Better Way to Declare Variables with :=

Go has a unique way of declaring variables using the := shorthand notation which both declares and assigns a variable without needing to use the var keyword. There are a couple of requirements that must be met before you can use the := syntax. Your variable must be declared inside of a function.

Let’s see how we can use the := syntax in our Go program.

package main

import "fmt"

func main() {

  // Declare a variable "city" of type city and set it's value to "Las Vegas"
  // Notice we omit the "var" keyword and type declaration
  city := "Las Vegas"

  fmt.Println(city) // "Las Vegas"
}

As mentioned before, the shorthand := syntax can only be used inside of a function. The shorthand notation is the prefered way of declaring variables in Go as it greatly increases readability. The downside is that the type will be inferred, so if you create a variable price = 21, the type of price will be of type int, when you might have meant for it to be a float32 for example.

Multiple Variable Declarations in Go

Up until know we’ve only worked with a small number of variables. Go gives us a couple of handy ways of declaring multiple variables. While we could always just create a new variable on a new line like this:

package main

import "fmt"

func main() {

  var firstName string
  var lastName string

  firstName = "Ado"
  lastName = "Kukic"

  fmt.Println(firstName, lastName)

}

There are better ways to do it. If all of our variables are of the same type, then we can do the following:

package main

import "fmt"

func main() {

  // Declare multiple variables of the same type
  // Declare the type of all the variables at the end
  var firstName, lastName string

  firstName = "Ado"
  lastName = "Kukic"

  fmt.Println(firstName, lastName)

}

You can also do this with the shorthand syntax:

package main

import "fmt"

func main() {

  firstName, lastName, age := "Ado", "Kukic", 29

  fmt.Println(firstName, lastName, age) // "Ado Kukic 29"
}

The benefit of the shorthand notation is that now you can mix and match types and Go will, at compile time, figure out the correct types for your variables.

There is one more way of declaring multiple variables with the var keyword.

package main

import "fmt"

func main() {

  var (
    firstName string
    lastName string
    age int
  )

  firstName = "Ado"
  lastName = "Kukic"
  age = 29

  fmt.Println(firstName, lastName, age)

}

With the above approach you could additionally declare and assign the value inside the parentheses and get the same result.

package main

import "fmt"

func main() {

  var (
    firstName = "Ado"
    lastName = "Kukic"
    age = 29
  )

  fmt.Println(firstName, lastName, age)

}

Use It or Lose It

If you’ve run any of the above programs without the fmt.Println function your program would have failed to execute and you would have gotten an error saying that you have declared a variable but not used it. In Go, each variable created must serve a purpose and be used somewhere in the program otherwise the code will not compile.

You may run into instances where you will need to declare a value but not use it. In that case, Go has a special variable declaration _ which will simply the discard the value it receives.

To see a concrete case of where this is useful, let’s say you had a function that returns two different values. This is not uncommon in Go, as functions can return multiple values. So let’s say you run this function, but only care about the first value returned.

package main

import "fmt"

func main() {
  firstName, lastName := user()

  fmt.Println(firstName, lastName)
}

func user() (string, string) {
  return "Ado", "Kukic"
}

If we wanted to just print out the first value returned and updated our code above to say fmt.Println(firstName) we would get an error saying that we have declared a variable lastName but havent used it. To fix this, we’ll use the _ declaration syntax to discard the second value and make our program work.

package main

import "fmt"

func main() {
  firstName, _ := user()

  fmt.Println(firstName)
}

func user() (string, string) {
  return "Ado", "Kukic"
}

In Go, many functions return multiple values and it is very common to see the first value be the data you are hoping to get and the second value be any error that may have occurred. In cases like this, some developers may decide to ignore the error value during early development. While you should always handle all your errors properly, I have been guilty of doing this when trying to quickly prototype, just remember to go back and handle those errors before pushing the code to production.

Variable Initial Values

If you do not assign a value when creating a variable, Go will assign a zero value for the type. Let’s see how this works.

package main

import "fmt"

func main() {

  var message string
  // Default value: ""

  var age int
  // Default value: 0

  var isValid bool
  // Default value: false

}

The default value for any numeric type will be 0. For boolean values the default is false and for strings it will be an empty string. While the Go programming language does have a type of nil, a string cannot be of this type.

Variable Redeclaration

The final element of Go variables we’ll look at is variable redecleration. In many programming languages, you cannot redeclare a variable in the same block. While this is generally true in Golang, there is a case in which you can redeclare a variable.

In Go, you are allowed to redeclare a variable if and only if you are doing so using the := shorthand variable declaration and are introducing at least one new variable. Let’s see an example of how this works.

package main

import "fmt"

func main(){
  
  // Declare a boolean variable called err
  err := false

  // Declare two boolean variables, success and err, which will create a new success variable and redeclare the err variable this time setting it to true
  success, err := false, true

  fmt.Println(success, err)

}

Variable redeclaration is mainly used for error checking in Go. This is due to the nature of the languages design principles when it comes to error handling.

Constants

Variables and constants go hand in hand, so our cheatsheet on variables wouldn’t be complete without discussing constants as well.

In Go, constants work very much the same as variables with the notable exception that constants cannot be declared with the shorthand := syntax. The other big exception is that while variables declared in Go must be used or the program will not compile, constants do not have to be used.

Constants in Go are declared using the const keyword and behave like constants in most other programming languages meaning that the value placed in the constant cannot be changed. Once a constant is created, it’s value is well constant.

package main

import "fmt"

const message string = "You can't change me"

func main() {

  const luckyNumber = 7

  fmt.Println(message)

}

As you can see in program above, we declared two constants but only used one. As with strings in Go, while we can declare the type explicitly, we can also omit it and let Go infer the type for us.

Unlike the convention in many programming languages where constants are generally declared with all caps, in Go, constants should be declared using mixed caps. The reason for this is that in Go, public/private or exported/unexported variables and functions are denoted by whether or not the first letter in the variable, constant, or function is uppercase or not. If it is, it is exported, if it’s not then it’s treated as a private variable, constant, or function. I’ll go into this more in depth in the cheatsheet on packages.

Conclusion

Go is a wonderful programming language that puts productivity front and center. Variables in Go are easy grasp and master, but also have a number of unique features that greatly improve readability and overall functionality. I hope you found this guide useful and give Go a chance in your next project. :)

Special Thanks

Kale Blakenship for pointing out issues with constants and shorthand declarations.

Newsletter!

Useful articles. Once a month. No spam.