Search code examples
initializationgo

Multiple initializers in a Go if statement


Just discovered Go, and am very curious so far. I know I'm just being lazy, but I want to know if it is possible to initialize multiple variables in an if statement. I know that the following is possible:

if x := 5; x == 5 {
    fmt.Printf("Whee!\n")
}

I've tried the following:

if x := 5, y := 38; x == 5 {
    fmt.Printf("Whee! %d\n", y)
}

if x := 5 && y := 38; x == 5 {
    fmt.Printf("Whee! %d\n", y)
}

But neither worked. I looked over the documentation on the Go website, so is there anything I am missing or is this simply not possible?


Solution

  • Here's how to do it:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        if x, y := 5, 38; x == 5 {
            fmt.Printf("Whee! %d\n", y)
        }
    }
    


    Tested with this revision:

    changeset:   3975:b51fd2d6c160
    tag:         tip
    user:        Kevin Ballard <xxxxxxxxxxxxxxxxxxxxx>
    date:        Tue Nov 10 20:05:24 2009 -0800
    summary:     Implement new emacs command M-x gofmt