douyou2732 2016-01-06 14:13
浏览 218
已采纳

从Go中的数组返回指针数组

Just so you know, I am quite new to Go.

I have been trying to make a function like this:

func PointersOf(slice []AnyType) []*AnyType{
    //create an slice of pointers to the elements of the slice parameter
}

It is like doing &slice[idx] for all elements in the slice, but I am having trouble with how to type my parameters and return type, as well as how to create the slice itself.

This method needs to work for slices of built-in types, as well as for slices of structs and slices of pointers to built-in types/structs

After invoking this function it would be preferable if I don't have to cast the pointer slice


Edit: The reason why I need this method is to have a generic way to use the elements of an array in a for ... range loop, in stead of using copies of that element. Consider:

type SomeStruct struct {
    x int
}

func main() {
    strSlice := make([]SomeStruct, 5)
    for _, elem := range strSlice {
        elem.x = 5
    }
}

This Doesn't work, because elem is a copy of the strSlice element.

type SomeStruct struct {
    x int
}

func main() {
    strSlice := make([]SomeStruct, 5)
    for _, elem := range PointersOf(strSlice) {
        (*elem).x = 5
    }
}

This however should work, since you only copy the pointer that points to an element in the original array.

  • 写回答

1条回答 默认 最新

  • doukang7858 2016-01-06 15:51
    关注

    Use the following code to loop through a slice of structs setting a field. There's no need to create a slice of pointers.

    type SomeStruct struct {
      x int
    }
    
    func main() {
      strSlice := make([]SomeStruct, 5)
      for i := range strSlice {
        strSlice[i].x = 5
      }
    }
    

    <kbd>playground example</kbd>

    Here's the proposed PointersOf function:

    func PointersOf(v interface{}) interface{} {
      in := reflect.ValueOf(v)
      out := reflect.MakeSlice(reflect.SliceOf(reflect.PtrTo(in.Type().Elem())), in.Len(), in.Len())
      for i := 0; i < in.Len(); i++ {
        out.Index(i).Set(in.Index(i).Addr())
      }
      return out.Interface()
    }
    

    and here's how to use it:

    for _, elem := range PointersOf(strSlice).([]*SomeStruct) {
        elem.x = 5
    }
    

    <kbd>playground example</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型