dongyuanliao6204 2017-05-11 17:17
浏览 34
已采纳

Golang如何在指针数组中范围

if I have PersonManager struct and it has *[]Person array. I want to range every item in this array. For example

manager := *PersonManager

for ii := 0; len(*manager.allPersons); ii++{
    fmt.Println(manager.allPersons[:ii].name)
}

for this example, manager variable is pointer and array that in this variable is pointer too. How can I range this items?

Not: I m getting cannot slice manager.allPersons (type *[]Person) error

  • 写回答

2条回答 默认 最新

  • duangong1979 2017-05-11 17:22
    关注

    Use the range keyword. https://github.com/golang/go/wiki/Range

    for i, person := range *manager.allPerson {
        fmt.Println(person.name)
    }
    

    Note that the compiler will be angry if you don't use the index var i. If you don't intend to use it, replace with _.

    To further explain, your original error was due to the fact that you correctly dereferenced your *[]Person the first time, but not inside the for loop.

    fmt.Println(manager.allPersons[:ii].name) // wrong
    fmt.Println((*manager.allPersons)[:ii].name) // right
    

    Also, given that your slice contains Person struct values, it will have to copy it if you use the optional second value in the range expression. Thus, it would be more efficient to keep using just the indexes.

    As a suggestion, don't use a *[]Person, use []*Person, which is probably what you intended to use anyway. A slice is already a pointer value. Using []*Person you don't have to fear a copy by the range expression because it is simply a pointer to a Person instead of the entire struct.

    In fact, unless you either change the type to []*Person or index into the slice you won't be able to have changes reflected in the slice because a struct value will be a copy in the range loop. See https://github.com/golang/go/wiki/Range#gotchas but be aware that if the value is a pointer value, this isn't an issue.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas
  • ¥15 蓝牙硬件,可以用哪几种方法控制手机点击和滑动
  • ¥15 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题