Introduction
Unlike other languages, Go only has the keyword "for" for loop statements. However, it is efficient and flexible. Let's learn about the for loop in Go.
Knowledge Points:
- For loop
- For range loop
Unlike other languages, Go only has the keyword "for" for loop statements. However, it is efficient and flexible. Let's learn about the for loop in Go.
Knowledge Points:
In the previous section on basic data structures, we learned that a string is a collection of characters. Therefore, we can use the index to retrieve specific characters in a string. Let's create a string.go
file and write the following code into it:
package main
import "fmt"
func main() {
s := "labex"
// Access each character in the string using indices
fmt.Println(s[0], s[1], s[2], s[3], s[4])
// Print characters
fmt.Printf("%c %c %c %c %c\n", s[0], s[1], s[2], s[3], s[4])
}
The output is as follows:
108 97 98 101 120
l a b e x
In this program, we declare a string variable to store "labex" and use the index to access each character in the string. When printing, we find that the program outputs numbers instead of actual characters.
By comparing the following ASCII table, we can see that the numbers correspond to the actual characters. For example, in the ASCII table, "108" corresponds to "l".
This is because characters actually store the numeric encoding of each character under the "UTF-8" encoding. "UTF-8" is compatible with "ASCII", so the position of the character "l" actually stores the numeric encoding "108".
If we want to output characters, we can use the fmt.Printf
function with the %c
escape sequence to output them as characters. This is demonstrated in the second line of the code. It will convert the numeric encoding to characters and then output them.
To access each character in the string in the string.go
file, we need to declare an index every time. This will be troublesome when dealing with hundreds or thousands of data. In this case, we can use a for loop to operate.
A loop executes a program based on a condition. Let's take a look at the syntax of the for loop statement:
for initialization; condition; post {
// code block
}
The initialization statement initializes a variable. The condition should return a boolean value. The post statement modifies the value of the variable in each loop iteration. Let's look at a specific example.
Create a for.go
file in the ~/project
directory and write the following content:
package main
import "fmt"
func main() {
// Output numbers from 0 to 9
for i := 0; i < 10; i++ {
fmt.Println(i)
}
}
The output is as follows:
0
1
2
3
4
5
6
7
8
9
In this program, we first initialize a temporary variable i
to 0, and in each loop iteration, the value of i
will be increased by 1. The condition is that the loop will continue if the value of i
is less than 10, which means that the program will output numbers from 0 to 9.
Note: In a for loop, the initialization, condition, and post statements are all optional. This means that even without these statements, the for loop will work normally.
If only the condition statement is present, the for loop functions similarly to a "while" loop in other languages.
The following code uses only the condition statement to achieve the same result as the previous program:
package main
import "fmt"
func main() {
i := 0
for i < 10 {
fmt.Println(i)
i++
}
}
You can see that when only the condition statement is present, the semicolon ;
used to separate statements can be omitted.
Now that we understand the syntax of the for loop, let's rewrite the first program in this section using a for loop:
package main
import "fmt"
func main() {
s := "labex"
for i := 0; i < len(s); i++ {
fmt.Printf("%d %c \n", s[i], s[i])
}
}
The output is as follows:
108 l
97 a
98 b
101 e
120 x
Let's do a quiz to consolidate our understanding of the for loop.
Create a for2.go
file. The task is to output each character in reverse order from the string "labex".
Expected Output:
x
e
b
a
l
Requirements:
for2.go
file should be placed in the ~/project
directory.Hint: The index starts from 0.
In the previous section, we mentioned that all three statements in a for loop are optional. What would happen if none of them were declared? Let's experiment.
Write the following code into the for.go
file:
package main
import "fmt"
func main() {
for {
fmt.Printf("1")
}
}
After running the program, we can see that if the condition in the for loop is not declared, the condition will be assumed to be true
and the loop will continue indefinitely.
111
Tip: Use Ctrl+C
to terminate the program.
If we want to exit the loop in a specified condition without declaring a condition statement or cannot write a condition statement, we can use the "break" keyword. It forces an immediate exit from the enclosing loop.
The following code uses the "break" keyword to output 23 "1"s:
package main
import "fmt"
func main() {
i := 0
for {
// Increase the value of i by 1 in each loop iteration
i++
fmt.Printf("1")
// Exit the loop when the value of i is 23
if i == 23 {
break
}
}
}
The "break" keyword can not only be used in a for loop without a condition statement, but it can also be used in a for loop with a condition statement. When the "break" condition is met, it will skip the condition statement and exit the loop.
In addition to the "break" keyword, which forces an immediate exit from the loop, there is also the "continue" keyword, which allows you to skip the rest of the current loop iteration and start the next iteration.
The usage of the "continue" keyword is similar to the "break" keyword, but their functions are different.
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
if i == 2 || i == 8 {
continue
}
fmt.Println(i)
}
}
After running the program, the output is as follows:
0
1
3
4
5
6
7
9
In this program, we added a condition statement in the code block of the for loop. If the current value of the loop variable is 2 or 8, it will skip the rest of the code and start the next loop iteration. Therefore, the output does not include the numbers 2 and 8.
In this lab, we learned about the for loop. Let's review:
Having learned about branching and looping statements, in the next experiment, we'll learn about the "goto" statement.