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])
}
相关推荐
Kenneth風车3 分钟前
【机器学习(七)】分类和回归任务-K-近邻 (KNN)算法-Sentosa_DSML社区版
人工智能·算法·低代码·机器学习·分类·数据分析·回归
视觉小鸟6 分钟前
【java面试每日五题之基础篇一】(仅个人理解)
java·笔记·面试
我是一颗小小的螺丝钉1 小时前
idea插件推荐之Cool Request
java·ide·intellij-idea
m0_631270402 小时前
标准C++(二)
开发语言·c++·算法
沫刃起2 小时前
Codeforces Round 972 (Div. 2) C. Lazy Narek
数据结构·c++·算法
爱coding的橙子2 小时前
CCF-CSP认证考试准备第十五天 202303-3 LDAP
算法
QXH2000003 小时前
Leetcode—环形链表||
c语言·数据结构·算法·leetcode·链表
小灰灰爱代码4 小时前
C++——判断year是不是闰年。
数据结构·c++·算法
小灰灰爱代码4 小时前
C++——求3个数中最大的数(分别考虑整数、双精度数、长整数数的情况),用函数重载方法。
数据结构·c++·算法
Kerwin要坚持日更4 小时前
Java小白一文讲清Java中集合相关的知识点(九)
java·开发语言