Chapter 8: Declare Multiple Variables

Declare Multiple Variables — one of Go’s nicest features for clean, readable code.

In Go, declaring multiple variables at once is very common and encouraged — it makes code shorter, groups related values, and is especially useful when:

  • Initializing several related values (width, height, color…)
  • Handling multiple return values from functions (value, error — the classic pattern)
  • Grouping config/options in a block

There are three main clean ways to declare multiple variables. I’ll explain each like we’re pair-programming: syntax, rules, when to choose which, pros/cons, and lots of copy-paste examples.

1. Using var with comma-separated list (Same type — explicit)

Syntax:

Go

or without values (zero values):

Go

Examples:

Go

When to use:

  • You want the type very visible (good for config structs or package-level vars)
  • All variables have the same type
  • At package level (outside functions)

2. Using var block — Group many variables (Very readable!)

Syntax:

Go

Real-world example (common in main or config):

Go

Why people love this:

  • Groups related declarations → easy to read/scan
  • Mix inferred and explicit types
  • Great for package-level or init-time setup
  • Looks clean in large structs/configs

3. Short declaration := with multiple values (Most idiomatic inside functions!)

Syntax:

Go

Rules & superpowers:

  • Types always inferred
  • Only inside functions
  • At least one must be new (allows re-assignment of others — very useful!)
  • Perfect for function returns (especially value, ok or value, err)

Examples:

Go

Output example:

text

Quick Comparison Table (Choose the Right Tool!)

Style Syntax Example Allowed Where Types Inferred? Re-declare allowed? Best For Idiomatic Score (2026)
var single-line same type var a, b int = 1, 2 Anywhere Optional No Same-type locals / package-level Medium
var ( … ) block var ( x=10; y=”hi”; z bool ) Anywhere Yes (if = value) No Grouping config/options, readability High
:= multiple x, y, z := 1, “two”, true Only functions Always Yes (if ≥1 new) Everyday function code, error handling, loops Very High

Common Patterns You’ll See Every Day in Real Go Code

  1. Error handling (almost always multiple :=):
Go
  1. Loop variables + index:
Go
  1. Coordinate / point:
Go
  1. Ignoring some returns:
Go

Your Quick Practice Exercise (Try Now!)

Create multi_vars.go and mix all styles:

Go

Run it — play with changing values, add re-declarations, try a var block.

Any part still fuzzy?

  • How re-declaration with := exactly works (shadowing vs reassignment)?
  • Multiple returns from your own functions?
  • When NOT to declare multiple (readability trade-offs)?
  • Or next: pointers with multiples? slices/maps init?

You’re mastering this fast — keep the questions coming! 💻🇮🇳 Let’s keep building! 🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *