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.
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)
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
Multiple Variable Declaration
or
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 |
Variable Scope
Local Variables
Package-Level Variables
Constants vs Variables
Variables can change; constants cannot.
Cannot assign later:
Type Conversion (Explicit Only)
Go does not allow implicit type conversion.
Shadowing Variables
A variable declared in inner scope can shadow outer variable.
- Interview favorite concept
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
Variable store data in Go
Use
varor:=to declareGo assigns zero values
Strongly typed language
No implicit type conversion
Important for Go interviews & backend dev
