If statements in Go
An if statement begins with the keyword if, followed by some expression whose value is true or false. This is the conditional expression which determines whether or not the code in the if statement will be executed.
1if x > 0 {
2 fmt.Println("x is positive")
3}
Else statements
Whereas an if statement on its own just does or doesn’t do something based on the condition, an if … else statement does one thing or another (but never both).
1fmt.Println("Let's see what the sign of x is:")
2if x <= 0 {
3 fmt.Println("x is zero or negative")
4} else {
5 fmt.Println("x is positive")
6}
7fmt.Println("Well, that clears that up!")
You can also write else if
statements:
1fmt.Println("Let's see what the sign of x is:")
2if x < 0 {
3 fmt.Println("x negative")
4} else if x == 0 {
5 fmt.Println("x is zero")
6} else {
7 fmt.Println("x is negative")
8}
9fmt.Println("Well, that clears that up!")
References
Next -> happy-path
Next -> early-return
Next -> compound-if-statements-in-go
#programming #control #statement #flow #basics #golang #if #conditional