Golang If-Else Statement
If-else is a conditional statement that is used to create conditional based programming. We use if statements to control the application flow.
The if statement consists of a conditional expression and executes only if the specified expression is true. If statement may have an optional else statement that executes when the specified expression is false.
Golang If Else Syntax
if conditional-expression {
// statements
}
In this syntax, if is a keyword that represents if statement and conditional-expression is a boolean expression.
The if statement does not require parenthesis around the expression but curly ({}) braces are required to enclose the code.
Go If Else Example
package main
import (
"fmt"
)
func main() {
a := -10;
if a>0{
fmt.Println("Value is positive integer");
}else{
fmt.Println("Value is negative integer");
}
}
Output:
Value is negative integer
Else is Optional Statement
package main
import (
"fmt"
)
func main() {
a := 10;
if a>0{
fmt.Println("Value is positive integer");
}
}
Output:
Value is positive integer
Example : Nested If
package main
import (
"fmt"
)
func main() {
a := 10;
if a>0{
fmt.Println("Value is positive integer");
if a%2 == 0 {
fmt.Println("value is even");
}
}
}
Output:
Value is positive integer
value is even
Example: Ladder If Else
package main
import (
"fmt"
)
func main() {
if a := 9; a==0{
fmt.Println("Value is Zero");
}else if a%2 == 0 {
fmt.Println("Value is multiple of 2");
}else if a%3==0 {
fmt.Println("Value is multiple of 3");
}else{
fmt.Println("Neighter multiple of 2 nor 3");
}
}
Output:
Value is multiple of 3
Go Ternary Operator
Go language does have ternary operator concept. We will have to use if statement for every use
Conclusion
In this tutorial, we learnt use of if, if else, nested if in go programming language. We discussed use of the control statements with the help of examples.
If we missed something, you can suggest us at - info.javaexercise.com