Declare Multiple Variables

Declaring Multiple Variables #

Go makes it easy to declare multiple variables at once, which helps keep your code clean and concise.


✅ Multiple Variables on the Same Line #

You can declare multiple variables of the same type in one line using the var keyword.

Example: #

package main

import "fmt"

func main() {
    var a, b, c, d int = 1, 3, 5, 7

    fmt.Println(a)
    fmt.Println(b)
    fmt.Println(c)
    fmt.Println(d)
}

👉 Note: When using the var keyword with explicit types, only one type can be specified per line.


✅ Multiple Variables of Different Types #

If the type is not explicitly specified, you can declare variables of different types on the same line.

Example: #

package main

import "fmt"

func main() {
    var a, b = 6, "Hello"
    c, d := 7, "World!"

    fmt.Println(a)
    fmt.Println(b)
    fmt.Println(c)
    fmt.Println(d)
}

Here, the compiler automatically infers the types of variables based on their assigned values.


✅ Grouped Variable Declarations (Block) #

For better readability and organization, you can group multiple variable declarations in a block.

Example: #

package main

import "fmt"

func main() {
    var (
        a int
        b int    = 1
        c string = "hello"
    )

    fmt.Println(a)  // Output: 0 (default int value)
    fmt.Println(b)  // Output: 1
    fmt.Println(c)  // Output: "hello"
}

👉 This approach is useful when declaring many variables, keeping the code organized and easy to read.


✅ Why Use Multiple Variable Declaration? #

  • Keeps code concise and clean.
  • Makes it easier to declare related variables together.
  • Helps maintain consistency and readability in larger programs.

🚀 Practice declaring multiple variables in your Go programs to write efficient and well-structured code.