Isaac
Isaac

Reputation: 12884

multiple temp variables at if/else scope

I've just noticed that we can declare a shadowing variable that scope to if/else statement as below

package main

import (
  "fmt"
)

func main() {
  num := 8


  if num := 9; num < 0 {
    fmt.Println(num, "is negative")
  } else if num < 10 {
    fmt.Println(num, "has 1 digit")
  } else {
    fmt.Println(num, "has multiple digits")
  }

  fmt.Println("num outside:",num)
}

Now my question is, is it true that I can only declare a single temp variable within a if/else statement?

I've tried both ways below but failed as hitting errors

//if num := 9; c := 10; num < 0 {..... //syntax error: c := 10 used as value

//if num := 9, c:= 10; num < 0 {..... //syntax error: unexpected :=, expecting semicolon or newline

Upvotes: 1

Views: 799

Answers (1)

leaf bebop
leaf bebop

Reputation: 8232

Why, Go has tuple assignments. Try:

if num,c:=9,10; num<0 {
//whatever
}

Now that we are at it, you should note that the optimal statement (the one before ;) can be more than assignments. It is legal to write:

if fmt.Println("something"); num<10 {
}

Upvotes: 3

Related Questions