Go语言现代web开发09 for 循环语句

Often, we need to execute a specific block of code multiple times. Loops are constructs that help us to do that. We can find multiple loops in various programming languages, but to keep things as simple as possible, the Go programming language has only one loop, for loop.

通常,我们需要多次执行特定的代码块。循环是帮助我们做到这一点的结构。我们可以在各种编程语言中找到多个循环,但为了使事情尽可能简单,Go编程语言只有一个循环,for循环。

The for loop consists of three statements separated with a semicolon, which comes after for keyword, as we can see in the following code example.

for循环由三个语句组成,其中以分号分隔,分号位于for关键字之后,如下面的代码示例所示。

go 复制代码
for i := 0; i < 10; i++ {
    a[i] = i * 2
}

The first statement, the init statement, will declare and initialize variables that will be visible in the scope of the loop (integer variable i). Init statement will be executed before the first iteration.

第一个语句,init语句,将声明并初始化在循环范围内可见的变量(整数变量i)。init语句将在第一次迭代之前执行。

The second statement, condition, has the same role as the condition in if statement. The condition will be evaluated before every iteration and if the result of the evaluation is positive (true), the next iteration will be executed.

第二个语句condition与if语句中的condition具有相同的作用。该条件将在每次迭代之前求值,如果求值的结果为正(true),则执行下一次迭代。

The third statement, the post statement, will update conditional and local variables. The post statement will be executed at the end of every iteration. In our example, operator ++ will increment the value of the variable.

第三个语句post语句将更新条件变量和局部变量。post语句将在每次迭代结束时执行。在我们的示例中,操作符++将增加变量的值。

The for loop from our example will initialize an integer array with ten elements.

示例中的for循环将初始化一个包含十个元素的整数数组。

Init and put statements are optional and they can be omitted (in that case, semicolons can be also omitted). We often omit these statements when there is no need to use local variables. This for loop will update the value of the variable result.

Init和put语句是可选的,可以省略它们(在这种情况下,分号也可以省略)。当不需要使用局部变量时,我们经常省略这些语句。这个for循环将更新变量result的值。

go 复制代码
for result < 500 {
    result *= sum * 2
}

Technically, we can also omit conditional statement. But without it, the loop will never stop iterating. These kinds of loops are called infinite loops.

从技术上讲,我们也可以省略条件语句。但是如果没有它,循环将永远不会停止迭代。这种循环被称为无限循环。

Range is a special from of for loop which used to iterate over slice and map. For each iteration, two values will be returned, an index and a value (copy of the element at the index). In the next example, we will iterate through slice and sum-only elements on even indexes.

Range是一个特殊的for循环,用于迭代slice和map。对于每次迭代,将返回两个值,一个索引和一个值(索引处元素的副本)。在下一个示例中,我们将遍历偶数索引上的仅切片和仅求和元素。

go 复制代码
for i, v := range arr {
    if i % 2 == 0 {
        sum += v
    }
}

The variable v is actually a copy of arr[i], so any modification of variable v will not affect the original slice. We can test this with the following code example.

变量v实际上是arr[i]的副本,因此对变量v的任何修改都不会影响原始切片。我们可以用下面的代码示例进行测试。

go 复制代码
a := []int{3, 33, 333}
for _, v := range a{
    v = v * v
}
fmt.Println(a)

In order to modify the original slice, the element must be accesses through an index.

为了修改原始片,必须通过索引访问元素。

Variable v is allocated only once, it will not e allocated for each iteration, so we should be very careful. In the following example, all elements of the second slice will point to the same variable that holds the last assigned value (three in our case).

变量v只分配一次,它不会为每次迭代分配,所以我们应该非常小心。在下面的示例中,第二个切片的所有元素都指向保存最后一个赋值的变量(在本例中为三个)。

go 复制代码
a := []int{3, 33, 333}
var b []*int

for _, v := range a {
    b = append(b, &v)
}

for _, v := range b {
    fmt.Println(*v)
}

The Go compiler does not allow the declaration of unused variables, but sometimes we do not need index or value. They can be ignored by assigning them to the _(underscore) operator. This operator is also know as a blank identifier.

Go编译器不允许声明未使用的变量,但有时我们不需要索引或值。可以通过将它们赋值给_(下划线)操作符来忽略它们。这个操作符也被称为空白标识符。

In this example, we decided to ignore the index.

在这个案例中,我们决定忽略索引。

go 复制代码
for _, v := range arr {
    sum += v
}

There are situations when it is not necessary to execute all iterations. With the continue statement, the remaining part of the current iteration will be skipped, and the next iteration will be executed. In the following example, all slice elements, except one on index 3 will be printed on standard output.

在某些情况下,没有必要执行所有迭代。使用continue语句,将跳过当前迭代的其余部分,并执行下一个迭代。在下面的示例中,除了索引3上的一个元素外,所有切片元素都将在标准输出中打印。

go 复制代码
a := []int{3, 33, 333, 3333, 33333}
for i := 0; i < 5; i++ {
    if i == 3{
        continue
    }
    fmt.Println(arr[i])
}

The break statement will terminate the execution of the current loop. This can be useful when we are looking for the index of an element with a specific value. When we find that element, we can stop the search and there is no need to execute the remaining iterations. In the next example, the loop will be terminated when the value of variable i is equal to 3.

break语句将终止当前循环的执行。这在查找具有特定值的元素的索引时非常有用。当我们找到那个元素时,我们可以停止搜索,并且不需要执行剩余的迭代。在下一个示例中,当变量i的值等于3时,循环将终止。

go 复制代码
for i := 0; i < 5; i++ {
    if i == 3{
        break
    }
    fmt.Println(a[i])
}
相关推荐
皮皮林5516 小时前
IDEA 源码阅读利器,你居然还不会?
java·intellij idea
卡尔特斯10 小时前
Android Kotlin 项目代理配置【详细步骤(可选)】
android·java·kotlin
白鲸开源10 小时前
Ubuntu 22 下 DolphinScheduler 3.x 伪集群部署实录
java·ubuntu·开源
ytadpole10 小时前
Java 25 新特性 更简洁、更高效、更现代
java·后端
纪莫11 小时前
A公司一面:类加载的过程是怎么样的? 双亲委派的优点和缺点? 产生fullGC的情况有哪些? spring的动态代理有哪些?区别是什么? 如何排查CPU使用率过高?
java·java面试⑧股
JavaGuide11 小时前
JDK 25(长期支持版) 发布,新特性解读!
java·后端
用户37215742613511 小时前
Java 轻松批量替换 Word 文档文字内容
java
白鲸开源11 小时前
教你数分钟内创建并运行一个 DolphinScheduler Workflow!
java
CoovallyAIHub12 小时前
中科大DSAI Lab团队多篇论文入选ICCV 2025,推动三维视觉与泛化感知技术突破
深度学习·算法·计算机视觉
Java中文社群12 小时前
有点意思!Java8后最有用新特性排行榜!
java·后端·面试