目前,我有一个包含以下代码的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
的构造函数该代码可以正常工作,但是在我每次使用
m := &ms[i]
循环时都必须编写for ... range
,我觉得应该有一种更友好的代码编写器来解决此问题。理想情况下,我希望可以进行以下操作(使用makeed&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”包的情况下在操场上运行):
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()
}