Go Variables - A Visual How-to Guide
Tags: go, programming
Published: 2017-10-11 14:02:44

---
title: Go Variables - A Visual How-to Guide
published: true
description: Easily understand Go variables with visual examples.
tags: go, golang, programming
---

![Go Variables](https://thepracticaldev.s3.amazonaws.com/i/xn65hnt21r9v4lv5xl5h.png)

## Beauty of Go declarations â¤ï¸

> Go defines the variables as they read. Go is explicit and simple.

Instead of doing the arithmetic of Clockwise/Spiral Rule[^1] to read a C declaration, Go uses a simpler approach for us humans.

#### â†’ C’s version:

![C Declaration](https://thepracticaldev.s3.amazonaws.com/i/eiuq0qqydyy65wjrujf9.png)
*Clockwise/Spiral Rule*

#### â†’ Go’s version:

![Go Declaration](https://thepracticaldev.s3.amazonaws.com/i/mr1rcf96wigukrmasvzf.png)
*Humanized*

---

## What is a variable in Go?

![What is a variable in Go?](https://thepracticaldev.s3.amazonaws.com/i/acp9w9q6ukzyxw2m3xum.png)

**Type** â†’ What kind of information can be stored inside the variable.

**Value** â†’ The stored value inside the variable.

**Address** â†’ Where the variable can be found in computer memory.

---

## Why do we need variables?

Without variables, there would be only static-data in our programs that we can’t change. **Variables let us do dynamic things**, such as getting user feedback, and re-using the same value again.

---

## How to declare a Go variable?

It’s better to talk about zero-values first. If you declare a variable without a value, then it’ll have a zero-value depending on the type of the variable.

![Zero Values](https://thepracticaldev.s3.amazonaws.com/i/j75ij597zm87wsffun01.png)
*Left side gets right side’s values if not initialized.*

---

## Long Declaration

![Long Variable Declaration](https://thepracticaldev.s3.amazonaws.com/i/v6n6ga6xaqdugmduzfty.png)

> Declares a variable named ageOfUniverse with type of int.

Name can be anything including unicodes like Ï€, âˆ‘, âˆ«, but not this: ðŸ˜±. Its value is a zero-value of an int which is 0.

---

## Short Declaration

![Short Variable Declaration](https://thepracticaldev.s3.amazonaws.com/i/bcech4nlaojjeuln4baa.png)

> Declares a variable named ageOfUniverse and stores a value of 14 billions in the variable and guesses its type automatically (type-inferring).

The variable is declared and its value and type are assigned all together with `:=` operator. When you use short declaration, Go will not use a zero-value assignment, obviously. ðŸ‘‹ *Pascal programmers may remember `:=`*.

ðŸ‘‰ *For more info, you may read the [Short Declarations Rulebook](https://blog.learngoprogramming.com/golang-short-variable-declaration-rules-6df88c881ee)*.

---

## Multiple declaration

![Multiple Variable Declaration](https://thepracticaldev.s3.amazonaws.com/i/8tw0dixhtybgxglstwkr.png)

> Declares multiple variables which have different types and values in the same statement.

The number of items on the left-hand side (*which is: livablePlanets and ageOfEarth*) should match to the number of items on the right-hand side (*which is: 1 and 4.5e9*).

---

## Multiple short declaration

![Multiple Short Variable Declaration](https://thepracticaldev.s3.amazonaws.com/i/g4mv389uc41ednzfb4fm.png)

> Declares two variables of type float64 and string; and assigns 14 billions to the first and “go” to the second variable.

---

## Assigning values

![Simple Assignment](https://thepracticaldev.s3.amazonaws.com/i/fmcfgeykmd5el3lon4yp.png)

![Multiple Assignment](https://thepracticaldev.s3.amazonaws.com/i/danz3t9p3xkdvbl02xae.png)

When you want to assign a wrong type of data to a variable, Go compiler will fail to compile.

![Wrong Assignment](https://thepracticaldev.s3.amazonaws.com/i/5v1xqdko66luplfxp30l.png)

---

## ðŸ’¡ Which declaration form should I use?

Use long declaration when you can’t know what data to store beforehand, otherwise, use short declaration. Use multiple declaration when you want to define multiple variables together or as an hint for code readability that the variables will be used together.

You can’t use short declarations outside of functions including main function. Or: you will meet with this error: *“syntax error: non-declaration statement outside function body”*.

---

## How variables are stored?

When we declare an integer variable, 4-bytes of storage space in the memory for the variable is reserved. When the data doesn’t fit into the variable, Go compiler will terminate.

However, *int* is a floppy type, its capacity can change. So, we can’t just simply store the age of the universe in an int variable. We should have used *uint64* instead. An *int* can’t store ~14 billions of years, it can only store up to ~4 billions of years on 32-bit machines. Or it will overflow, but for a 64-bit machine, compilation will work.

![How Golang Variables are Stored](https://thepracticaldev.s3.amazonaws.com/i/9e7yohlsrt6xnbrtvx3s.png)

Try it yourself.

```go
package main

import (
	"fmt"
	"unsafe"
)

func main() {
	var ageOfUniverse int
	reservedBytes := unsafe.Sizeof(ageOfUniverse)

	fmt.Printf("Number of bytes reserved for `ageOfUniverse` variable is %d bytes.\n",
		reservedBytes)
}
```
*[Play with it](https://play.golang.org/p/SV95kReYNm): Example shows you how many bytes the ageOfUniverse variable can store.*

```go
package main

import (
	"fmt"
)

// on 32-bit machines, it'll overflow
// on 64-bit machines, everything is fine
// use: uint64 instead.
func main() {
	var ageOfUniverse int = 14e9 // 14e9 = 14 and 9 zeros which is 14 billions

	fmt.Printf("`ageOfUniverse` is %d.\n", ageOfUniverse)
}
```
*Incorrect code. [Run it to see yourself](https://play.golang.org/p/IOQjUKSIC1).*

```go
package main

import (
	"fmt"
)

func main() {
 	// still not a good way to define a variable like this. we will see it.
	var ageOfUniverse uint64 = 14e9 // 14e9 = 14 and 9 zeros which is 14 billions

	fmt.Printf("`ageOfUniverse` is %d.\n", ageOfUniverse)
}
```
*Correct-ish code. [Run it](https://play.golang.org/p/q5fnpQCqxl).*

---

## Making a variable accessible to other packages

This is called *exporting*. To define a variable in the package scope, you can only use long declaration or multiple declaration. After that, you need to capitalize its first letter.

![Making a variable accessible to other packages](https://thepracticaldev.s3.amazonaws.com/i/2674kaicaeuk1ypomz3b.png)

---

ðŸ”¥ **I’m creating an online course for Go: [Join to my newsletter](http://eepurl.com/c4DMNX)**!
*Let’s stay in touch weekly for new tutorials and for my online Go course.*

----

â¤ï¸ **[Please Share this post on twitter](http://bit.ly/golang-variables)**!

ðŸ¦ I’m mostly tweeting about Go: [@inancgumus](https://twitter.com/inancgumus).

----

[^1]: http://c-faq.com/decl/spiral.anderson.html

*This article originally published as [Learn Go variables–A visual guide](https://blog.learngoprogramming.com/learn-go-lang-variables-visual-tutorial-and-ebook-9a061d29babe) in [Learn Go Programming](https://blog.learngoprogramming.com).*