English 中文(简体)
Multiple initializers in a Go if statement
原标题:

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

I ve tried the following:

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

if x := 5 && y := 38; x == 5 {
    fmt.Printf("Whee! %d
", 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?

最佳回答

Here s how to do it:

package main

import (
    "fmt"
)

func main() {
    if x, y := 5, 38; x == 5 {
        fmt.Printf("Whee! %d
", 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
", y)
        fmt.Printf("x = %d
", x)
    }
}

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





相关问题
Nested struct variable initialization

How can I initialize this nested struct in C? typedef struct _s0 { int size; double * elems; }StructInner ; typedef struct _s1 { StructInner a, b, c, d, e; long f; char[16] s; }...

How to create a side scroller game?

I want to create a game where the user can go to the right-most part of the screen, and if they go any further, they will slide into a new view. So basically, if they have 3 monsters chasing them on ...

Is Shared ReadOnly lazyloaded?

I was wondering when I write Shared ReadOnly Variable As DataType = New DataType() Or alternatively Shared ReadOnly Variable As New DataType() Is it lazy loaded or as the instance initializes? ...

Multiple initializers in a Go if statement

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

热门标签