Go Variables

Last Updated: March 18, 2022

Variable declaration in GO

var i int
var i int = 10
var i:=42

var n complex64 = 1 + 2i // complex type variables

You have to use all the variables you declared otherwise it will give your compiler error.

When you redeclare a variable

var i int = 10
i := 20

You will get a compile error

./prog.go:9:4: no new variables on left side of :=

Go Lang Variable Shadowing

package main

import "fmt"
var i int = 10

func main() {
	if true {
		var i int = 50
	fmt.Println(i) // 10

Why the value of i is not equal to 51?

var i int = 50 declare a new variable but it is a shadow of the original variable i. But later variable i is for the scope of the if statement.

Detect Variable Shadowing

You use vet to detect variable shadowing

> go vet -shadow main.go

Go Variable Scope

  • Package level