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.

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

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容