If the statement is used to specify a block of Go Code to be executed if a condition is True.
Syntax:
If condition {
// conditions
}
In the example below, we test two values to find out if 200 is greater than 180. If the condition is true, print some text
package main import "fmt" func main() { x := 200 y := 180 if x > y { fmt.Println("x is greater than y") } }
Output :
PS C:\GO_Language\conditions> go run if.go x is greater than y
Syntax: If condition { // executed if the condition is false }else { // executed if the condition is false }
package main import "fmt" func main() { time := 20 if (time < 18) { fmt.Println("Good day.") } else { fmt.Println("Good evening.") } }
Output :
PS C:\GO_Language\conditions> go run ifelse.go Good evening.
package main import ("fmt") func main() { temperature := 14 if (temperature > 15) { fmt.Println("It is warm out there") } else { fmt.Println("It is cold out there") } }
Output :
PS C:\GO_Language\conditions> go run ifelse2.go It is cold out there
package main import "fmt" func main() { temperature := 14 if (temperature > 15) { fmt.Println("It is warm out there.") } // this raises an error else { fmt.Println("It is cold out there.") } }
Output :
PS C:\GO_Language\conditions> go run ifelse3.go # command-line-arguments .\ifelse3.go:10:3: syntax error: unexpected else, expecting }
else if statement is used to specify a new condition if the first condition is false.
Syntax: if condition1 { // executed if condition1 is true } else if condition2 { // executed if condition1 is false and condition2 is true } else { // executed if condition1 and condition2 are both false }
package main import "fmt" func main() { time := 22 if time < 10 { fmt.Println("Good morning.") } else if time < 20 { fmt.Println("Good day.") } else { fmt.Println("Good evening.") } }
Output :
PS C:\GO_Language\conditions> go run ifils4.go Good evening.
package main import "fmt" func main() { a := 14 b := 14 if a < b { fmt.Println("a is less than b.") } else if a > b { fmt.Println("a is more than b.") go run } else { fmt.Println("a and b are equal.") } }
Output :
PS C:\GO_Language\conditions> go run ifelse5.go a and b are equal.
package main import "fmt" func main() { x := 30 if x >= 10 { fmt.Println("x is larger than or equal to 10.") } else if x > 20 fmt.Println("x is larger than 20.") } else { fmt.Println("x is less than 10.") } }
Output :
PS C:\GO_Language\conditions> go run ifelse6.go x is larger than or equal to 10.
Combining Conditional Statements in Golang