英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论