目前我有一个包含以下代码的go程序。
package main
import "time"
import "minions/minion"
func main() {
// creating the slice
ms := make([]*minion.Minion, 2)
//populating the slice and make the elements start doing something
for i := range ms {
m := &ms[i]
*m = minion.NewMinion()
(*m).Start()
}
// wait while the minions do all the work
time.Sleep(time.Millisecond * 500)
// make the elements of the slice stop with what they were doing
for i := range ms {
m := &ms[i]
(*m).Stop()
}
}
这里的 NewMinion()
是一个构造函数,它返回一个 *minion.Minion
代码运行完美,但每次我使用 for ... range
循环时都必须编写 m := &ms[i]
在我看来应该成为代码编写者更友好的方式来解决这个问题。
理想情况下,我希望像下面这样的东西成为可能(使用组成的 &range 标签):
package main
import "time"
import "minions/minion"
func main() {
// creating the slice
ms := make([]*minion.Minion, 2)
//populating the slice and make the elements start doing something
for _, m := &range ms {
*m = minion.NewMinion()
(*m).Start()
}
// wait while the minions do all the work
time.Sleep(time.Millisecond * 500)
// make the elements of the slice stop with what they were doing
for _, m := &range ms {
(*m).Stop()
}
}
不幸的是,这还不是一个语言特性。关于从代码中删除 m := &ms[i]
的最佳方式的任何考虑?或者还有没有比这更省力的方法?
最佳答案
你的第一个例子是一个指针 slice ,你不需要每次都获取 slice 中指针的地址然后取消引用指针。更地道的 Go 看起来像(略微编辑以在没有“minion”包的情况下在 Playground 上运行):
http://play.golang.org/p/88WsCVonaL
// creating the slice
ms := make([]*Minion, 2)
//populating the slice and make the elements start doing something
for i := range ms {
ms[i] = NewMinion(i)
ms[i].Start()
// (or equivalently)
// m := MewMinion(i)
// m.Start()
// ms[i] = m
}
// wait while the minions do all the work
time.Sleep(time.Millisecond * 500)
// make the elements of the slice stop with what they were doing
for _, m := range ms {
m.Stop()
}
关于for-loop - 转到如何正确使用 for ... range 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34636862/