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:
|
0 1 2 3 4 5 6 |
var var1, var2, var3 Type = value1, value2, value3 |
or without values (zero values):
|
0 1 2 3 4 5 6 |
var var1, var2 Type |
Examples:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package main import "fmt" func main() { // Same type, with values var width, height int = 1920, 1080 var red, green, blue uint8 = 255, 128, 0 // No values → all get zero value var x, y, z int // x=0, y=0, z=0 // Mixed — but all must share the same type here var a, b float64 = 3.14, 2.718 fmt.Printf("Resolution: %dx%d\n", width, height) fmt.Printf("RGB: (%d, %d, %d)\n", red, green, blue) fmt.Println("Zeros:", x, y, z) } |
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:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
var ( name string = "Webliance" age int = 25 city = "Hyderabad" // type inferred here too! temperature int isActive bool = true ) |
Real-world example (common in main or config):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var ( // Server settings port int = 8080 debug bool = true timeout = 30 * time.Second // inferred time.Duration // User info username string points int = 0 // Constants-like maxUsers = 1000 ) |
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:
|
0 1 2 3 4 5 6 |
var1, var2, var3 := value1, value2, value3 |
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:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
func main() { // Simple multiple lat, long, city := 17.3850, 78.4867, "Hyderabad" // Classic error handling pattern // file, err := os.Open("config.json") // data, status, err := fetchAPI("https://api.example.com") // Redeclaration magic (re-assign existing + declare new) count := 10 count, name, active := 15, "Webliance", true // count reassigned, name & active new // From function that returns multiple a, b := swap("left", "right") // imagine func swap(x, y string) (string, string) fmt.Println(lat, long, city) fmt.Println("Count now:", count, "Name:", name, "Active:", active) } // Example helper func swap(x, y string) (string, string) { return y, x } |
Output example:
|
0 1 2 3 4 5 6 7 |
17.385 78.4867 Hyderabad Count now: 15 Name: Webliance Active: true |
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
- Error handling (almost always multiple :=):
|
0 1 2 3 4 5 6 7 |
body, err := io.ReadAll(resp.Body) rows, err := db.Query("SELECT * FROM users") |
- Loop variables + index:
|
0 1 2 3 4 5 6 7 8 |
for i, v := range fruits { // i and v declared here } |
- Coordinate / point:
|
0 1 2 3 4 5 6 |
x, y := mouse.Position() |
- Ignoring some returns:
|
0 1 2 3 4 5 6 |
value, _ := expensiveComputation() |
Your Quick Practice Exercise (Try Now!)
Create multi_vars.go and mix all styles:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package main import "fmt" var ( defaultPort = 8080 version = "1.0.0" ) func main() { var r, g, b uint8 = 100, 150, 200 x, y, z := 3.5, -2.1, "point" status, code, message := true, 200, "OK" fmt.Printf("Colors: %d %d %d\n", r, g, b) fmt.Printf("Point: %.1f, %.1f (%s)\n", x, y, z) fmt.Printf("Status: %t | Code: %d | %s\n", status, code, message) } |
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! 🚀
