Go if Statement

Introduction

Go if statement can execute a block of code when a certain condition is true.

if condition { 
    // code to run if condition is true
}
package main /*  ww w .j  av a2s  .co  m*/

import (
  "fmt"
)
func main() {
  x := true
  if x {
    fmt.Println("Here")
  }
}

The if....else statement.

if  condition { 
    // code to run if condition is true
} else {
    // code to run if condition is false
}
package main /*from www.ja v  a  2  s. co  m*/

import (
  "fmt"
)
func main() {
  x := 100
  if x == 100 {
    fmt.Println("Equal")
  } else {
    fmt.Println("Not Equal")
  }
}

The if...else if...else statement.

if  condition-1 { 
    // code to run if condition-1 is true
} else if condition-2 {
    // code to run if condition-2 is true
} else {
    // code to run if both condition1 and condition2 are false
}
package main/* ww  w  .ja  v a2  s  .  c  o  m*/
import (
  "fmt"
)

func main() {
  x := 100

  if x == 50 {
    fmt.Println("50")
  } else if x == 100 {
    fmt.Println("100")
  } else {
    fmt.Println("Not 50 and Not 100")
  }
}

The if statement can have a composite statement.

The condition expression is after the initialization statement.

if var declaration; condition { 
    // code to run if condition is true
}
package main /* w w  w . java  2s.  com*/

import (
  "fmt"
)
 
func main() {
  if x := 100; x == 100 {
    fmt.Println("100")
  }
}



PreviousNext

Related