Go Multiple Variable Declaration
Go (Golang) – Multiple Variable Declaration
Go allows you to declare and initialize multiple variables in a clean and readable way. This helps reduce code length and improves clarity.
1️⃣ Multiple Variables of the Same Type
Syntax
With Values
2️⃣ Multiple Variables with Different Types
Using var Block (Recommended)
✔ Clean
✔ Readable
✔ Commonly used for global variables
3️⃣ Type Inference with Multiple Variables
Go automatically detects the types.
4️⃣ Short Declaration (:=) with Multiple Variables
Used inside functions only.
⚠️ Rule:
-
At least one variable must be new when reusing
:=
5️⃣ Multiple Assignment (Swapping Values)
Go allows swapping without a temporary variable.
6️⃣ Multiple Return Values (Function Example)
7️⃣ Blank Identifier (_) in Multiple Declaration
Used to ignore unwanted values.
Summary Table
| Method | Example |
|---|---|
| Same type | var a, b int |
| Different types | var (a int; b string) |
| Type inference | var x, y = 1, 2 |
| Short declaration | x, y := 5, 6 |
| Swap values | a, b = b, a |
| Ignore value | _ |
