Zero Values in Golang

Learn via video courses
Topics Covered

Overview

In this article, We will understand "Golang Zero values" or default values. What are the different zero values for all data types and implement examples to get zero values of some commonly used datatypes.

Introduction

Variables are the nouns of a programming language; all variables in Golang have a data type. A variable's data type determines the values that the variable can hold and the operations that can be performed on that variable.

In Golang var keyword is used to declare variables. Below is the syntax to declare a variable in Golang.

Zero Values

In Golang, When we create a variable with the help of either a normal var keyword or by using new or make keywords without any explicit initialization of a variable, We allocate only memory for such variable, and values of such types are automatically initialized with their zeroed value. Zero values act as default values when we don't initialize the variable.

Importance of Zero Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable Zero value by Golang. This Property of setting the values of variables to Zero values is critical for the safety of your program. This makes the life of a developer easy as we don't need to think about initializing the variable that we don't want to.

Let's take an example of an integer array, If we don't have the concept of zero values, We need to set all values just to satisfy the compiler and for the normal working of an array. This explains to us how it's very critical for us that default values are assigned to variables in the background so that we can focus on writing the code.

Zero Value of Data Types

Below are Zero values of different data types in Golang.

TypeZero Value
Integer0
Float0.0
Complex0 Real and 0 Imaginary
Byte0
Rune0
String""
Boolfalse
Mapnil
Channelnil
Interfacenil
Slicesnil
Pointernil

Example

Output :

Zero value example : link

Conclusion

  • Explained the concept of Zero values in Golang.
  • Implemented examples for Zero values and described their importance of them in Golang.