for-loop - 转到如何正确使用 for ... range 循环

标签 for-loop go range slice

目前我有一个包含以下代码的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/

相关文章:

Windows批处理FOR循环范围通过命令行

java - 在另一个循环中再次使用在一个循环中创建的具有相同值的数组

go - 如何从golang中的base64编码文件中提取文件扩展名?

objective-c - C 或 Obj-c 函数将范围标准化为 x-y

java - 增强了对象的 for 循环和 null 检查

c - 如何解决这个特殊的嵌套 for 循环练习?

algorithm - 将平面列表加权为正态分布

templates - 多路平等测试失败

范围减少的Javascript数组

ruby - 如何测试两个时间范围是否重叠?