18.Conditional - If Statement - Programming in GO
Conditional - If Statement
If Statements
bool
true
false
- the not operator
!
- initialization statement
if
/else
if
/else
if
/else
if
/else if
/…/else
If statements are conditional statements. Remember in control flow, we have sequence, we have iterative, and we also have conditional. Sequence is top to bottom, iterative is looping, and conditional is based upon a condition it will either do one thing or another.
Let’s start with some predeclared constants, true
and false
and not true !true
and not false !false
package main
import (
"fmt"
)
func main() {
if true {
fmt.Println("001")
}
if false {
fmt.Println("002")
}
if !true {
fmt.Println("003")
}
if !false {
fmt.Println("004")
}
}
Following through the example above, we see if true
which will always be true, and will execute. if false
will always be false, and will not execute. if !true
is if not true, which is the same as false, and will not execute, while if !false
is if not false, which will execute.
Let’s try with some more examples using numbers and the not operator !
:
package main
import (
"fmt"
)
func main() {
if 2 == 2 {
fmt.Println("001")
}
if 2 != 2 {
fmt.Println("002")
}
if !(2 == 2) {
fmt.Println("003")
}
if !(2 != 2) {
fmt.Println("004")
}
}
In Go, we mostly don’t see semicolons at the end of statements in source. Though we do see them in initialization statments.
So, if we want to have two statements on one line, we can use a semicolon.
package main
import (
"fmt"
)
func main() {
fmt.Println("here's a statement"); fmt.Println("something else")
}
If you run format, the formatter will put this over two lines.
One usecase would be initialization of a variable and evaluation, for example if x := 42; x == 2
will initialize the variable x
with the value of 42
then will evaluation the expression x == 2
which is false
package main
import (
"fmt"
)
func main() {
if x := 42; x == 2 {
fmt.Println("001")
}
fmt.Println("here's a statement")
fmt.Println("something else")
}