Let’s talk variable declaration in Go. Could you explain what is a variable “zero value”?

Technology CommunityCategory: GolangLet’s talk variable declaration in Go. Could you explain what is a variable “zero value”?
VietMX Staff asked 3 years ago

Variable is the name given to a memory location to store a value of a specific type. There are various syntaxes to declare variables in go.

// 1 - variable declaration, then assignment
var age int
age = 29

// 2 - variable declaration with initial value
var age2 int = 29

// 3 - Type inference
var age3 = 29

// 4 - declaring multiple variables
var width, height int = 100, 50

// 5 - declare variables belonging to different types in a single statement
var (  
      name1 = initialvalue1,
      name2 = initialvalue2
)
// 6 - short hand declaration
name, age4 := "naveen", 29 //short hand declaration

If a variable is not assigned any value, go automatically initialises it with theĀ zero value of the variable’s type. Go is strongly typed, so variables declared as belonging to one type cannot be assigned a value of another type.