在Go语言的if语句中使用多个初始化器

huangapple go评论157阅读模式
英文:

Multiple initializers in a Go if statement

问题

刚刚发现了Go语言,到目前为止非常好奇。
我知道我只是懒惰,但我想知道是否可以在if语句中初始化多个变量。我知道以下是可以的:

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

我尝试了以下代码:

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)
}

但是都没有成功。我查看了Go官方网站上的文档,所以我是否遗漏了什么,或者这根本不可能实现?

英文:

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?

答案1

得分: 24

这是如何做的:

package main

import (
	"fmt"
)

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

测试使用此修订版本:

changeset:   3975:b51fd2d6c160
tag:         tip
user:        Kevin Ballard <xxxxxxxxxxxxxxxxxxxxx>
date:        Tue Nov 10 20:05:24 2009 -0800
summary:     实现新的emacs命令M-x gofmt
英文:

Here's how to do it:

package main

import (
	&quot;fmt&quot;
)

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

<br>
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

答案2

得分: -1

包 main
导入(“fmt”)
功能主要()
{
如果 x,y := 5, 38; x == 5 {
fmt.Printf(“y =%d\n”,y)
fmt.Printf(“x =%d\n”,x)
}
}

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

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

huangapple
  • 本文由 发表于 2009年11月12日 06:03:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/1718376.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定