Go语言中的for range循环是否有更简洁的形式?

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

Is there a shorter form for Go for range loops

问题

我已经检查了语言规范 - 有没有更简单的方法来表达这个:

for _, month := range []int{4,6,9,11} {
    fmt.Print(month, " ")
}

我(理想情况下)希望有像这样的方式(我知道这不是Go语言):

for month in [4,6,9,11] {
    fmt.Print(month, " ")
}

我知道我可以这样做:

days30 := []int{4,6,9,11} 
for i := range days30 {
    fmt.Print(days30[i], " ")
}

但这样不够可读...

注意:这是为了教学目的 - 所以我正在寻找一个简单、自包含的解决方案,适用于学生 - 请不要使用太高级的方法。

英文:

I have checked the language spec - is there a simpler way to say this:

for _, month := range []int{4,6,9,11} {
	fmt.Print(month, " ")
}

I'm (ideally) looking for something like (I know this isn't Go)

for month in [4,6,9,11] {
	fmt.Print(month, " ")
}

I know I can do:

days30 := []int{4,6,9,11} 
for i := range days30 {
	fmt.Print(days30[i], " ")
}

But this is less readible...

Note: This is for teaching purposes - so I'm looking for a simple, self contained solution for students - nothing too advanced please.

答案1

得分: 21

不。

英文:

No.​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

答案2

得分: 1

简短回答,不会。在切片上使用range函数时,始终会返回索引或索引和值。

英文:

Short answer, no. Using range on a slice will always either yield the index or index,value.

huangapple
  • 本文由 发表于 2015年1月18日 20:34:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/28009708.html
匿名

发表评论

匿名网友

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

确定