英文:
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 (
"fmt"
)
func main() {
if x, y := 5, 38; x == 5 {
fmt.Printf("Whee! %d\n", 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("fmt")
func main() {
if x, y := 5, 38; x == 5 {
fmt.Printf("y = %d\n", y)
fmt.Printf("x = %d\n", x)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论