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

var a, b, c int

With Values

var x, y, z int = 10, 20, 30

2️⃣ Multiple Variables with Different Types

Using var Block (Recommended)

var (
name string = "Sanjit"
age int = 25
active bool = true
)

✔ Clean
✔ Readable
✔ Commonly used for global variables


3️⃣ Type Inference with Multiple Variables

var city, country = "Delhi", "India"

Go automatically detects the types.


4️⃣ Short Declaration (:=) with Multiple Variables

Used inside functions only.

x, y := 5, 10
name, age := "Amit", 30

⚠️ Rule:

  • At least one variable must be new when reusing :=

x := 10
x, y := 20, 30 // ✅ y is new
x := 10
x := 20 // ❌ error (no new variable)

5️⃣ Multiple Assignment (Swapping Values)

Go allows swapping without a temporary variable.

a, b := 10, 20
a, b = b, a

6️⃣ Multiple Return Values (Function Example)

func calc(a, b int) (int, int) {
return a + b, a * b
}

sum, product := calc(5, 3)


7️⃣ Blank Identifier (_) in Multiple Declaration

Used to ignore unwanted values.

sum, _ := calc(5, 3)

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 _

You may also like...