Go Multiple Variables

In Go, you can declare multiple variables in a single statement, making your code cleaner and more concise.

Tutorials dojo strip



Declaring Multiple Variables in a Single Line

Go allows the declaration of multiple variables of the same type in a single line by using the type keyword once.

Example:

package main

import ("fmt")

func main() {
  var yamaha, honda, suzuki, kawasaki int = 1, 3, 5, 7

  fmt.Println(yamaha)
  fmt.Println(honda)
  fmt.Println(suzuki)
  fmt.Println(kawasaki)
}




Declaring Variables Without Specifying a Type

If the type keyword is omitted, you can declare multiple variables with different types in one line.

Example:

package main

import ("fmt")

func main() {
  var yamaha, suzuki = 6, "Riding Fun"
  honda, kawasaki := 7, "High Performance"

  fmt.Println(yamaha)
  fmt.Println(suzuki)
  fmt.Println(honda)
  fmt.Println(kawasaki)
}




Declaring Multiple Variables in a Block

Multiple variable declarations can also be grouped into a block for better readability.

Example:

package main

import ("fmt")

func main() {
  var (
    yamaha   int
    honda    int = 1
    suzuki   string = "Leading Innovation"
  )

  fmt.Println(yamaha)
  fmt.Println(honda)
  fmt.Println(suzuki)
}
Tutorials dojo strip
Scroll to Top