Go If
Go If statement is used to conditionally execute a block of statements, based on the result of a boolean condition/expression.
In this tutorial, we will learn the syntax and usage of If statement in Go language.
Syntax
The syntax of Go If statement is
</>
Copy
if condition {
//code
}
where the condition is a boolean expression or evaluates to a boolean value. If the expression evaluates to true, the code inside the if block executes, else the code in If block is not executed.
Examples
In the following example, we will print a message based on a condition.
example.go
</>
Copy
package main
import "fmt"
func main() {
var a int = 10
var b int = 20
if a < b {
fmt.Println("a is less than b")
}
}
Output
a is less than b
In the following program, we will use Go If Statement and check if a number given in x is even.
example.go
</>
Copy
package main
import "fmt"
func main() {
var x = 14
if x%2 == 0 {
fmt.Println("x is even.")
}
fmt.Println("Bye.")
}
Output
x is even.
Bye.
Conclusion
In this Go Tutorial, we learned about Go If statement, its syntax and its usage with the help of example programs.
