Difference between identifier and expression in Go

huangapple go评论148阅读模式
英文:

Difference between identifier and expression in Go

问题

http://golang.org/ref/spec#RangeClause

RangeClause = ( ExpressionList "=" | IdentifierList ":=" ) "range" Expression .

试图理解range子句,特别是标识符和表达式之间的区别。

谢谢。

英文:

http://golang.org/ref/spec#RangeClause

RangeClause = ( ExpressionList "=" | IdentifierList ":=" ) "range" Expression .

Trying to understand the range clause and specifically the difference between an identifier and an expression

Thanks.

答案1

得分: 5

使用range关键字,您可以迭代许多内容并在此过程中分配结果。
您可以分配给两个内容:

  • 标识符(通过IdentifierList
  • 表达式(通过ExpressionList

标识符

这些是内部循环中用于使用的新变量。它们必须遵守标识符的规则(Unicode名称,无空格等)。如果使用这些变量,您必须在列表和range关键字之间使用:=运算符。

示例:

for i := range []int{1,2,3} {
	fmt.Println(i)
}

表达式

您不一定需要声明新变量,可以使用现有变量,甚至可以评估返回存储位置的表达式。以下是一些示例:

分配给指针(Play):

var i = 0

func main() {
	p := &i

	for *p = range []int{1,2,3} {
		fmt.Println(i)
	}
}

返回指针并分配给它(Play):

var i = 0

func foo() *int {
	return &i
}

func main() {
	for *foo() = range []int{1,2,3} {
		fmt.Println(i)
	}
}
英文:

With the range keyword you can iterate over many things and assign the results while doing so.
You can assign to two things:

  • Identifiers (via IdentifierList)
  • Expressions (via ExpressionList)

Identifiers

These are new variables for use in the inner loop. They must obey the rules for identifiers (unicode names, no whitespaces, etc.). If you use these you have to use the := operator between the list an the range keyword.

Example:

for i := range []int{1,2,3} {
	fmt.Println(i)
}

Expressions

You don't necessarily need to declare new variables, you can use existing ones and even
have expressions evaluated which return the storage location. A few examples:

Assign to a pointer (Play):

var i = 0

func main() {
	p := &i

	for *p = range []int{1,2,3} {
		fmt.Println(i)
	}
}

Return a pointer and assign it (Play):

var i = 0

func foo() *int {
	return &i
}

func main() {
	for *foo() = range []int{1,2,3} {
		fmt.Println(i)
	}
}

huangapple
  • 本文由 发表于 2013年11月8日 06:39:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/19848176.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定