Go Variables
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)
2️⃣ Variable Declaration Methods ⭐
Method-1: var with Type
Method- 2: var with Initialization
Method 3: Type Inference
Method 4: Short Variable Declaration := ⭐ (Most Used)
📌 Allowed inside functions only
3️⃣ Multiple Variable Declaration ⭐
or
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 |
5️⃣ Variable Scope ⭐
Local Variables
Package-Level Variables
6️⃣ Constants vs Variables ⭐
Variables can change; constants cannot.
❌ Cannot assign later:
7️⃣ Type Conversion (Explicit Only) ⭐
Go does not allow implicit type conversion.
8️⃣ Shadowing Variables ⚠️
A variable declared in inner scope can shadow outer variable.
📌 Interview favorite concept
9️⃣ Using _ (Blank Identifier) ⭐
Used to ignore values.
🔟 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
varor:=to declare -
Go assigns zero values
-
Strongly typed language
-
No implicit type conversion
-
Important for Go interviews & backend dev
