return 来自 Go 数组的指针数组

return array of pointers from an array in Go

如你所知,我是 Go 的新手。

我一直在尝试制作这样的功能:

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

这就像对切片中的所有元素执行 &slice[idx],但我在如何键入参数和 return 类型以及如何创建切片本身方面遇到了问题。

此方法需要适用于内置类型的切片,以及结构切片和指向内置指针的切片 types/structs

调用此函数后,如果我不必强制转换指针切片会更可取


编辑: 我需要这种方法的原因是有一种通用的方法来在 for ... range 循环中使用数组的元素,而不是使用该元素的副本。考虑:

type SomeStruct struct {
    x int
}

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

这不起作用,因为 elem 是 strSlice 元素的副本。

type SomeStruct struct {
    x int
}

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

但这应该有效,因为您只复制指向原始数组中元素的指针。

使用以下代码循环遍历设置字段的结构片段。无需创建指针切片。

type SomeStruct struct {
  x int
}

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

playground example

这是建议的 PointersOf 函数:

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

使用方法如下:

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

playground example