doufu1950 2016-01-06 15:32
浏览 53
已采纳

转到如何正确使用for…range循环

At the moment I have a go program that contains the following code.

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()
    }
}

Here NewMinion() is a constructor that returns a *minion.Minion

The code works perfectly, but having to write m := &ms[i] every time I use a for ... range loop seems to me like there should be a code writer friendlier way to tackle this problem.

Ideally I'd like something like the following to be possible (using the made up &range tag):

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()
    }
}

Unfortunately, this is not a language feature as of yet. Any considerations on what would be the nicest way remove the m := &ms[i] from the code? Or is there no way yet that takes less effort to write than this?

  • 写回答

2条回答 默认 最新

  • duanqian1888 2016-01-06 15:40
    关注

    Your first example is a slice of pointers, you don't need to take the address of the pointers in the slice and then dereference the pointers each time. More idiomatic Go would look like (edited slightly to run in the playground without the "minion" package):

    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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功