Pergunta

Apenas descoberto Go, e estou muito curioso até agora. Eu sei que eu apenas estou sendo preguiçoso, mas eu quero saber se é possível inicializar múltiplas variáveis ??em uma instrução if. Eu sei que o seguinte é possível:

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

Eu tentei o seguinte:

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

Mas nem trabalhou. Eu olhei a documentação no site do Go, então há algo que eu estou ausente ou é simplesmente não é possível?

Foi útil?

Solução

Aqui está como fazê-lo:

package main

import (
    "fmt"
)

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


Testado com esta revisão:

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

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top