目前我有一个包含以下代码的 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循环时都必须编写,在我看来应该有一种代码编写者更友好的方法来解决这个问题。
理想情况下,我希望以下内容成为可能(使用合成的 &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]从代码中删除 的最好方法有什么考虑吗?或者有没有比这更省力的写法?
白板的微信
侃侃尔雅
相关分类