Go provides conditionals/branching via If/Else and Switch statements. These works mostly as they are intended to work, or one have seen them working in other programming languages. Here is very basic If statement in Go
packagemainimport"fmt"funcmain() {if10%2==0 { fmt.Println("10 is even") }}// 10 is even
In Go, if statement returns true, block assigned to it will be evaluated, otherwise not. A If statement can be combined with else to give an option when statement evaluates to false. Lets change our example we used before
packagemainimport"fmt"funcmain() {var value =9if value%2==0 { fmt.Printf("%d is even", value) } else { fmt.Printf("%d is odd", value) }}// 9 is odd
Simple, right. If/else can have multiple if else combined together making it more realistic to real world problems, like following
packagemainimport"fmt"funcmain() {var bmi =9if value%2==0 { fmt.Printf("%d is even", value) } else { fmt.Printf("%d is odd", value) }}
Here is BMI categories as available on wikipedia. Lets create a simple Go program that would tell one, which category does one falls into
Change bmi value and see what would be program output
If with short statement
In Go, If statement allows a short statement just before the condition; seperated by ; and it would executed before conditional statement. For illustration consider following example
packagemainimport"fmt"funcmain() {if value :=7; value%2==0 { fmt.Printf("%d is even", value) } else { fmt.Printf("%d is odd", value) }}// 7 is odd