Yashwardhan Pauranik
Yashwardhan Pauranik

Reputation: 5566

Why Go returns value 0 to an unassigned integer variable?

I was asked to declare a variable of integer type as:

var someInteger int8

Later when I printed this variable, it prints the value 0.

My Go Program looks like:

package main

import "fmt"

func main() {
  var someInteger int
  fmt.Println(someInteger)      // Prints 0 in terminal
}

My question is since I haven't assigned any value, so it should return some Garbage value like C instead of behaving like static variables, which automatically initialize by value 0.

Upvotes: 1

Views: 1613

Answers (2)

Wardhan
Wardhan

Reputation: 66

Go makes this thing easy by adding sensible default values based on the type of the variables. For example:

var someInteger int8         // will print 0 as default
var someFloat float32        // will print 0 as default
var someString string        // will print nothing as it prints empty string
var someBoolean bool         // will print false as default

As @icza mentioned in his answer you can read more about it here

Upvotes: 3

icza
icza

Reputation: 418257

In Go you can't access uninitialized variables / memory. If you don't initialize a variable explicitly, it will be initialized implicitly to the zero value of its type.

This is covered in Spec: Variable declarations:

If a list of expressions is given, the variables are initialized with the expressions following the rules for assignments. Otherwise, each variable is initialized to its zero value.

Also mentioned at Spec: Variables:

If a variable has not yet been assigned a value, its value is the zero value for its type.

And also covered in the Go Tour: Zero Values which I highly recommend to take if you're learning the language.

Variables declared without an explicit initial value are given their zero value.

Upvotes: 10

Related Questions