Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
This stage is all about control structures; program structures that control which code runs next. First up, we'll look at loops, which cause a block of code to execute over and over.
- The
for
keyword is used for all loops in Go. - The most basic type of
for
loop looks similar to what you see in other C-like languages:- init statement
- condition
- post statement
- Followed by block
- Block code executed on each pass through loop
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
fmt.Println(i)
}
}
- Post statement can be whatever you want
-
i++
,i--
(change init/condition accordingly) -
i += 1
,i += 2
- But don't fail to increment it! If we used
i += 0
, for example, we'd have an infinite loop and would have to press Ctrl-C to interrupt the program.
-
Block scope rules apply to for
loops:
package main
import "fmt"
func main() {
beforeLoop := 888
for i := 1; i <= 5; i++ {
inLoop := 999
fmt.Println(i)
}
fmt.Println(beforeLoop) // OK
fmt.Println(i) // Error!
fmt.Println(inLoop) // 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
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