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 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,