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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献