
If Statements
booltruefalse
- the not operator
!
- initialization statement
if/elseif/elseif/elseif/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")
}
About the author
- DevRel at StackGen | Formerly at Deepfence ,Tenable , Accurics | AWS Community Builder also Docker Community Award Winner at Dockercon2020 | CyberSecurity Innovator of Year 2023 award by Bsides Bangalore | Docker/HashiCorp Meetup Organiser Bangalore & Co-Author of Learn Lightweight Kubernetes with k3s (2019) , Packt Publication & also run Non Profit CloudNativeFolks / CloudSecCorner Community To Empower Free Education reach out me twitterhttps://twitter.com/sangamtwts or just follow on GitHub -> https://github.com/sangam14 for Valuable Resources
Comments
Join the discussionNo comments yet. Be the first to comment.



