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
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
forkeyword is used for all loops in Go. - The most basic type of
forloop 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
First up, well look at loops which cause
a block of code to execute over and over.
0:00
The for key word is used for
all loops and go.
0:02
The most basic type of for
0:05
loop looks similar to what you
see in other C like languages.
0:06
There's an init statement,
which is usually use to set up a variable.
0:09
A condition statement,
0:14
which causes the code to continue
looping until the condition is false.
0:15
And a post statement, which runs
after each iteration of the loop.
0:20
This is followed by a block
of code within curly braces.
0:24
The code within the block gets executed
on each pass through the loop.
0:28
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