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}

main.go
flag := true
if flag {
fmt.Println("Flag is present")
}

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.

main.go
count := 1
if "hello" {
fmt.Println("Invalid if")
}
if count {
fmt.Println("Invalid if")
}

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

main.go
marks := 70
if marks > 80 {
fmt.Println("Great!")
} else if marks > 60 {
fmt.Println("Good!")
} else if marks > 40 {
fmt.Println("You can do better!")
}

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. The if-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