On a previous article we discussed all about variables. However, declaring variables is just one piece of the equation. Since go does not have nulls, would you be able to tell what value each primitive type is assigned?
If you though zero values then you're right. But would you be able to tell how to declare and use them
On this article let's continue our discussion on variable initialization in Go discussing Zero Values.
Zero Values
One important difference between Go and other programming languages is that in Go, a variable cannot be null (or undefined). In Go, variables declared and not initialized will have a default value associated to them also known as Zero Value.
Zero values are an important concept of Go and worth understanding well regardless of your programming skills. One of the big advantages they provide is that, by not having nulls, your code will not be subject to Null Pointer Exceptions, one of the biggest reason for bugs, crashes and security issues in other programming languages.
How to set Zero Values?
But how do we set variables to their zero values? If you read our previous tutorial you know that every variable non-initialized by default set its zero value.
Confusing? Better learn from an example then.
On the program below, none of variables was initialized thus, set to their respective zero value. Would you be able to tell what's this program outputs?
If you guessed 0 0 false "" [ ] congratulations! So let's see which are the zero values for the most common types.
Zero Values for Common Types
The zero values for the most common types:
- int, float64 (and other numeric types): 0
- bool: false
- string: "" (empty string)
- arrays/slices: [ ] (empty, not null/nil)
- custom types: {} (we'll learn about them later)
When to use Zero Values?
The last topic to cover about zero values is when to use them? Well, if you have experience in other programming languages you understand that you don't always have the value you need at hand. For all these use cases, you should declare your variables without initializing them. For example:
Conclusion
On this article we learned about Zero Values in Go. Zero Values are an important concept in Go that's worth understanding as they're widely used in Go programs and libraries. Learning and using Zero Values is important to make your code more robust and readable.