Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Go Language Overview!
You have completed Go Language Overview!
Preview
An "if" statement is a control structure that causes a block of code to run only under certain conditions.
- An
ifstatement is a control structure that causes a block of code to run only under certain conditions.- A condition followed by a block; block code is executed only if condition is true
package main
import (
"fmt"
)
func main() {
if true {
fmt.Println("true") // printed
}
if false {
fmt.Println("false") // not printed
}
if 1 < 2 {
fmt.Println("1 < 2") // printed
}
if 1 > 2 {
fmt.Println("1 > 2") // not printed
}
}
- Boolean operators:
-
!: "not" -
&&: "and" -
||: "or"
-
package main
import "fmt"
func main() {
if !true {
fmt.Println("!true") // not printed
}
if !false {
fmt.Println("!false") // printed
}
if true && false {
fmt.Println("true && false") // not printed
}
if true && true {
fmt.Println("true && true") // printed
}
if true || false {
fmt.Println("true || false") // printed
}
if true || true {
fmt.Println("true || true") // printed
}
}
-
else- Runs a block of code if no
ifcondition is true
- Runs a block of code if no
package main
import "fmt"
func main() {
if false {
fmt.Println("if") // not printed
} else {
fmt.Println("else") // printed
}
}
-
else if: A condition that's checked only if preceding conditions were false
package main
import "fmt"
func main() {
if false {
fmt.Println("if") // not printed
} else if true {
fmt.Println("else if") // printed
} else {
fmt.Println("else") // not printed
}
}
- Block scope rules apply to
ifblock
package main
import "fmt"
func main() {
beforeIf := 888
if true {
withinIf := 999
fmt.Println("if")
}
fmt.Println(beforeIf) // OK
fmt.Println(withinIf) // Error!
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
It consists of a condition
followed by a block of code and
0:00
the code in the block is run
only if the condition is true.
0:00
So here we have an if statement and
0:04
the condition is the literal boolean value
trick, which of course evaluates the true.
0:05
So the code here in the block
does get executed and
0:11
it prints out the string true.
0:15
You can see that down here in the output.
0:18
Here's another if statement, where
the condition is a simple boolean value,
0:20
it's the value false.
0:24
And, of course, false is not true, so
the code in the block does not run.
0:26
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up