go for range遍历

  1. range表达式
  2. 表达式左边

range表达式

The range expression x is evaluated once before beginning the loop, with one exception: if at most one iteration variable is present and len(x) is constant, the range expression is not evaluated.

备注: 至多只有一个迭代变量,且len(x)是常量,见go说明文档https://golang.org/ref/spec#Length_and_capacity

The expression len(s) is constant if s is a string constant. The expressions len(s) and cap(s) are constants if the type of s is an array or pointer to an array and the expression s does not contain channel receives or (non-constant) function calls; in this case s is not evaluated. Otherwise, invocations of len and cap are not constant and s is evaluated.

表达式左边

Function calls on the left are evaluated once per iteration. For each iteration, iteration values are produced as follows if the respective iteration variables are present:
https://golang.org/ref/spec For statements with range clause
注意string的遍历, 例子:

s := "he你好"
for idx, val := range s {
   fmt.Println("idx:", idx, ",val:", string(val))
}

output:
idx: 0, val: h
idx: 1, val: e
idx: 2, val: 你
idx: 5, val: 好

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至yj.mapple@gmail.com

文章标题:go for range遍历

文章字数:220

本文作者:melonshell

发布时间:2020-11-15, 10:40:11

最后更新:2020-11-21, 16:32:45

原始链接:http://melonshell.github.io/2020/11/15/go19_for_range/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏

相册