Can you declared multiple types of variables in single declaration in Go?

Yes, you can declare multiple variables of different types in a single declaration statement in Go. Go allows you to use the shorthand syntax for declaring and initializing multiple variables within the same block.

Here’s an example of declaring multiple variables of different types in a single line:

package main

import "fmt"

func main() {
    // Multiple variables of different types in a single declaration.
    var name string
    var age int
    var isStudent bool

    // Initialize the variables.
    name = "John Doe"
    age = 30
    isStudent = false

    fmt.Println("Name:", name)
    fmt.Println("Age:", age)
    fmt.Println("Is Student:", isStudent)
}

However, Go also provides a more concise way to declare and initialize variables of different types using the := short variable declaration syntax:

package main

import "fmt"

func main() {
    // Shorthand declaration and initialization of multiple variables.
    name := "John Doe"
    age := 30
    isStudent := false

    fmt.Println("Name:", name)
    fmt.Println("Age:", age)
    fmt.Println("Is Student:", isStudent)
}

Using the := syntax, Go infers the variable types from the assigned values. The short variable declaration is commonly used in Go for initializing variables when their types can be easily determined from the right-hand side of the assignment.

Both the long and short variable declaration methods allow you to declare and initialize multiple variables of different types in a single line, making Go code more concise and readable.

error: Content is protected !!