开发者

Multiple initializers in a Go if statement

开发者 https://www.devze.com 2022-12-10 23:35 出处:网络
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 poss

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 G开发者_如何学编程o website, so is there anything I am missing or is this simply not possible?


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


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

https://play.golang.org/p/Sbv6hUmKyA

0

精彩评论

暂无评论...
验证码 换一张
取 消