Variables in Golang

Author

Gurleen Sethi on 19 April 2022

Variables in Golang

Getting Started #

Go takes slightly different approach for variable declaration compared to other languages such as Java or JavaScript, it is not wildly different but there are some details that you need to understand to get a good grasp of the language.

I would recommend you to try out all the examples 👨🏻‍💻 the more you practice the more you understand and the more you retain. Go Playground and GoPlay are good online websites to quickly write and run some go code.

Defining Variables #

Here is a basic variable declaration in Go.

package main

import "fmt"

var y string = "Hello World" // 👈 Defining a global string variable `y`

func main() {
	var x int = 10  // 👈 Defining an int variable `x`
    fmt.Println(x)
}

Let's break it down:

  • var is the keyword we use to delacre a mutable variable.
  • x is the name of our variable.
  • int is the type of the variable.

Format to delcare variables becomes 👉 var <variable name> <variable type>.

We can also just delcare the variable and don't need to assign any value to it.

package main

import "fmt"

func main() {
	var x int
    fmt.Println(x) // Prints the 'zero value' of x
}

This will print the zero value of x which in this case is 0 because x is of type int.

Zero Values #

In Go if you delcare a variable and don't assign it a value, it gets assigned a zero value based on the type of the variable. Think of this as the default value provided by Go.

The zero values are based on the type of the variable. Here are some types in Go and their zero values:

Type Zero Value
int 0
float64 0.0
bool false
string ""
Slice nil
Pointer nil

Best way to find the zero value of a type is to declare a variable and print it.

package main

import "fmt"

func main() {
	var x int
	var y bool
	fmt.Println(x)  // Prints '0'
	fmt.Println(y)  // Prints 'false'
}

Type Inference #

Go lets you omit specifying a type when declaraing a variable, it can infer the type from the value that is being assigned.

package main

import "fmt"

func getValue() string {
	return "Hello World"
}

func main() {
	var a = 10 // 👈 `a` is of type int
	var b = getValue() // 👈 `b` is of type string
	fmt.Println(a, b)
}

Note, when omitting the type you have to assign the variable a value while declaring it, else go will not be able to infer the type 🤷‍♂️.

Assigning multiple variables #

Go allows you to delcare multiple variables at a time and also of different types. Here are some ways to do that.

package main

import "fmt"

func main() {
	var a, b int // Declaraing multiple variables at once
	var c, d = "Hello", "World" // Multiple variables omitting type (type inference)
	var e, f = 12, "ABC" // Multiple variables of different type
    
	var (
		g int     = 10
		h string  = "Bye"
		i float64 = 1.34
	)
    
    // Omiting Types
	var (
		j = 71
		k = "Hi!"
	)

	fmt.Println(a, b, c, d, e, f, g, h, i, j, k)
}

Constants with const keyword #

There is another way to define variables using the const keyword, as the name suggests it a way to define constants, but the important thing to note is that you can define only compile time constants using the const keyboard.

A compile time constant means this is valid:

package main

import "fmt"

func main() {
	const a = 10  // 👈 defining a const
	fmt.Println(a)
}

But the below example will not compile because the value cannot be determined during compile time.

package main

import "fmt"

func getValue() int {
	return 10
}

func main() {
	const a = getValue() // ❌ invalid, will not compile
	fmt.Println(a)
}

You can only define character, string, boolean and numeric constants in golang.

Using Short Hand Form #

Go is famous for its short hand form assignment operator :=. This operator allows you to define variables without the need to use the var keyword or specifying a type for the variable.

package main

import "fmt"

func getValue() string {
	return "Hello World"
}

func main() {
	a := 10 // 👈 `a` is of type int
	b := getValue() // 👈 `b` is of type string
	fmt.Println(a, b)
}

Go infers the type of variable a from the value it is being assigned, so to use := operator you need to asign a value to the variable so that go can determine the type. Therefore if you don't know the value of variable during its declaration use the var keyword to delcare the variable.

Assigning multiple variables #

Using the shorthand form you can assign more than one variables at a time.

package main

import "fmt"

func main() {
	a, b := 1, "Hello World" // 👈 Two new variables
	fmt.Println(a, b)
}

Shorthand form also allows you to re-assign the value of an already declared variable provided there is atleast a new variable being declared.

package main

import "fmt"

func main() {
	a := 1
	a, b := 2, "Hello World" // 👈 new variable `b` and changing value of existing `a`
	fmt.Println(a, b)  // Prints `2 Hello World`
}

But if there are no new variables being defined on the left hand side, the program will not compile.

package main

import "fmt"

func main() {
	a := 1
	b := "Hello"

	a, b := 2, "Hello World" // ❌ Produces the error `9:7: no new variables on left side of :=`
	fmt.Println(a, b)
}

🎉 You have reached the end of this article, there is so much more to the simple yet so deep concept of variables but what you learned in this article should be enough to let you move forward in your journey of golang.

Table of Contents
Subscribe via email

Get notified once/twice per month when new articles are published.

Byte Byte Go Affiliate
TheDeveloperCafe
Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.