donkey199024 2015-06-20 15:38
浏览 108
已采纳

Go中的for循环构造与range关键字之间的区别

Consider the following code which just prints all the ENV vars

package main

import (
    "fmt"
    "os"
)

func main() {
    for i, env := range os.Environ() {
        fmt.Println(i, env)
    }
}

Here, os.Environ() is supposed to return array of strings([] string), to loop over it. I need to to use range keyword & also for loop. Question is:

  1. Why are both for & range required? is it possible to use for loop for this as []string is already an array & we can iterate over arrays right?
  2. In the above code what does range do? and what does for loop does?

Sorry if this question is too stupid, I am just starting with Go

  • 写回答

1条回答 默认 最新

  • duanjiu2701 2015-06-20 15:41
    关注

    As mentioned in Range Clauses:

    A range clause provides a way to iterate over a array, slice, string, map, or channel.

    If you want to iterate over an []string, you need range.

    A For statement doesn't always use range.

    ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
    

    You have:

    • In its simplest form, a "for" statement specifies the repeated execution of a block as long as a boolean condition evaluates to true

    • A "for" statement with a ForClause is also controlled by its condition, but additionally it may specify an init and a post statement, such as an assignment, an increment or decrement statement

    • A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables if present and then executes the block.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab