【问题标题】:Multiple initializers in a Go if statementGo if 语句中的多个初始值设定项
【发布时间】:2010-12-15 15:48:45
【问题描述】:

刚刚发现 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 网站上的文档,有什么我遗漏的或者这根本不可能吗?

【问题讨论】:

  • 这个答案可能会通过给出“都不起作用”时得到的错误消息来改进。这样,人们在谷歌搜索他们做同样事情时遇到的错误时更有可能找到它。对我来说,我得到syntax error: a, _ := some.FunctionCall(x, y) used as value

标签: initialization go


【解决方案1】:

这是怎么做的:

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:     Implement new emacs command M-x gofmt

【讨论】:

    【解决方案2】:
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多