Like all other programming languages, Go has traditional if-else statements; the main difference is the lack of parentheses around the condition:
Syntax
1234567
ifcondition{//Do stuff in first condition ...}elseifotherCondition{//Do stuff in otherCondition...}else{//Do stuff if none of the above is satisfied ...}
count:=6ifcount<10{fmt.Printf("Count is below 10 at value %d\n",count)}// Output = "Count is below 10 at value 6"count=51ifcount%2==0{fmt.Printf("Count is even!\n")}else{fmt.Printf("Count is odd!\n")}//Output = "Count is odd!"count=25ifcount%15==0{fmt.Printf("FizzBuzz\n")}elseifcount%5==0{fmt.Printf("Buzz\n")}elseifcount%3==0{fmt.Printf("Fizz\n")}else{fmt.Printf("NoneOfTheAbove\n")}//Output = "Buzz"
In the above example, we check to see if a count is divsible by a certain number, and the respective case is executed.
If with Short Assignment
In Go, the user can assign a variable and condition on that variable on the same line (separated by a :), like the following
1234
ifshortStatementInt:=32;shortStatementInt>30{fmt.Printf("shortStatementInt is above 30!\n")}//Output = "shortStatementInt is above 30!"
In the above example, shortStatementInt is assigned, then evaluated in the condition following the :