Go Variables

Go Tutorial

Go Variables – Complete Tutorial

In Go (Golang), variables are used to store data values that can be used and modified during program execution.
Go provides simple, strict, and efficient ways to declare variables.


1️⃣ What is a Variable in Go?

A variable:

  • Stores a value in memory

  • Has a name, type, and value

  • Type is mandatory (explicit or inferred)

var x int = 10

2️⃣ Variable Declaration Methods ⭐

Method-1: var with Type

var age int
age = 25

Method- 2: var with Initialization

var name string = "Amit"

Method 3: Type Inference

var marks = 90 // inferred as int

Method 4: Short Variable Declaration := ⭐ (Most Used)

city := "Kolkata"

📌 Allowed inside functions only


3️⃣ Multiple Variable Declaration ⭐

var a, b, c int = 1, 2, 3

or

x, y := 10, 20

4️⃣ Zero Values in Go ⭐ (Very Important)

If a variable is declared but not initialized, Go assigns a zero value.

Type Zero Value
int 0
float 0.0
string ""
bool false
pointer nil
var isActive bool
fmt.Println(isActive) // false

5️⃣ Variable Scope ⭐

Local Variables

func test() {
x := 10
}

Package-Level Variables

var version = "1.0"

6️⃣ Constants vs Variables ⭐

Variables can change; constants cannot.

const pi = 3.14

❌ Cannot assign later:

// pi = 3.15 ❌

7️⃣ Type Conversion (Explicit Only) ⭐

Go does not allow implicit type conversion.

var a int = 10
var b float64 = float64(a)

8️⃣ Shadowing Variables ⚠️

A variable declared in inner scope can shadow outer variable.

x := 10
{
x := 20
fmt.Println(x) // 20
}
fmt.Println(x) // 10

📌 Interview favorite concept


9️⃣ Using _ (Blank Identifier) ⭐

Used to ignore values.

_, err := fmt.Println("Hello")

🔟 Common Mistakes ❌

❌ Using := outside function
❌ Expecting implicit type conversion
❌ Forgetting zero values
❌ Variable shadowing unintentionally


📌 Interview Questions & MCQs

Q1. Which operator is used for short variable declaration?

A) =
B) :=
C) ==
D) ->

Answer: B


Q2. Can := be used outside a function?

A) Yes
B) No

Answer: B


Q3. Zero value of string?

A) nil
B) " "
C) ""
D) 0

Answer: C


Q4. Does Go allow implicit type conversion?

A) Yes
B) No

Answer: B


Q5. What is variable shadowing?

A) Error
B) Variable overwrite
C) Inner variable hides outer
D) Type mismatch

Answer: C


🔥 Real-Life Use Cases

✔ Configuration values
✔ API parameters
✔ Counters & flags
✔ Data storage
✔ System programming


✅ Summary

  • Variables store data in Go

  • Use var or := to declare

  • Go assigns zero values

  • Strongly typed language

  • No implicit type conversion

  • Important for Go interviews & backend dev

You may also like...