Branching: If/Else
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
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
Simple, right. If/else can have multiple if else combined together making it more realistic to real world problems, like following
Here is BMI categories as available on wikipedia. Lets create a simple Go program that would tell one, which category does one falls into
Category
From
To
Very severely underweight
15
Severely underweight
15
16
Underweight
16
18.5
Normal (healthy weight)
18.5
25
Overweight
25
30
Obese Class I (Moderately obese)
30
35
Obese Class II (Severely obese)
35
40
Obese Class III (Very severely obese)
40
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
Last updated