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关键字之后,如下面的代码示例所示。

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的值。

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。对于每次迭代,将返回两个值,一个索引和一个值(索引处元素的副本)。在下一个示例中,我们将遍历偶数索引上的仅切片和仅求和元素。

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的任何修改都不会影响原始切片。我们可以用下面的代码示例进行测试。

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

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.
在这个案例中,我们决定忽略索引。

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上的一个元素外,所有切片元素都将在标准输出中打印。

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时,循环将终止。

for i := 0; i < 5; i++ {
    if i == 3{
        break
    }
    fmt.Println(a[i])
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Python私教

创业不易,请打赏支持我一点吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值