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.