Zero-initialization
Zero-initialization is a source of confusion sometimes. They are default values for many types that are assigned even if you don't provide a value for the definition. Following are the zero-initialization for various types:
- The
false
initialization forbool
type. - Using
0
values forint
type. - Using
0.0
forfloat
type. - Using
""
(empty strings) forstring
type. - Using
nil
keyword for pointers, functions, interfaces, slices, channels and maps. - Empty
struct
for structures without fields. - Zero-initialized
struct
for structures with fields. The zero value of a structure is defined as the structure that has its fields initialized as zero value too.
Zero-initialization is important when programming in Go because you won't be able to return a nil
value if you have to return an int
type or a struct
. Keep this in mind, for example, in functions where you have to return a bool
value. Imagine that you want to know if a number is divisible by a different number but you pass 0
(zero) as the divisor.
func main() { res := divisibleBy(10,0) fmt.Printf("%v\n", res) } func divisibleBy(n, divisor int) bool { if divisor == 0 { //You cannot divide by zero return false } return (n % divisor == 0) }
The output of this program is false
but this is incorrect. A number divided by zero is an error, it's not that 10 isn't divisible by zero but that a number cannot be divided by zero by definition. Zero-initialization is making things awkward in this situation. So, how can we solve this error? Consider the following code:
func main() { res, err := divisibleBy(10,0) if err != nil { log.Fatal(err) } log.Printf("%v\n", res) } func divisibleBy(n, divisor int) (bool, error) { if divisor == 0 { //You cannot divide by zero return false, errors.New("A number cannot be divided by zero") } return (n % divisor == 0), nil }
We're dividing 10
by 0
again but now the output of this function is A number cannot be divided by zero
. Error captured, the program finished gracefully.