【发布时间】:2016-04-10 18:20:04
【问题描述】:
目前我有一个包含以下代码的 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] 的最佳方法是什么?还是没有比这更省力的写法了?
【问题讨论】: