Go if语句中的多个初始化器 [英] Multiple initializers in a Go if statement

查看:56
本文介绍了Go if语句中的多个初始化器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚发现了Go,到目前为止我一直很好奇.我知道我只是在偷懒,但是我想知道是否可以在if语句中初始化多个变量.我知道以下是可能的:

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

我尝试了以下操作:

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网站上的文档,所以我有什么想念的吗?还是根本不可能?

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?

推荐答案

方法如下:

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

这篇关于Go if语句中的多个初始化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆