16. If Else
Control the flow
If Statement
If like in most other programming languages, is used to control flow of execution based on condition. Common semantic for if statement is
if condition { code to execute}
Stronger Semantics
If statement in Go has stronger semantics than some other programming languages. We can not provide integer or string as condition for if statement.Condition has to be a Boolean value in if statement. Following code will not compile.
Also, when code to execute is single statement, some programming languages allow to skip curly braces, but not in Go. As with other code blocks, curly braces need to start from same line.
Multiple Branches
To work with multiple branches, Go provide if...else
form
Remember that once a if condition is satisfied, it will not check for remaining conditions in other else blocks.
Ternary Operator
Go does not have ternary operator. This has been well addressed in Go FAQ.
The reason
?:
is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. Theif-else
form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct. - https://golang.org/doc/faq#Does_Go_have_a_ternary_form
GitHub Code
Last updated