2
votes

I have the following structure in Golang

type mystruct struct {
        Name  string
        Power int
    }

My purpose is to write a function that takes as input a slice of type *mystuct and returns a slice of type int containing the "Power" property taken from the input slice.

my code is presented below:

package main
import (
    "fmt"
)
func main() {
    obj := make([]*mystruct, 15)
    for i, s := range obj {
        s.Power = i
    }
    fmt.Println(extractpowers(obj))
}
func extractpowers(obj []*mystruct) []int {
    powers := make([]int, len(obj))
    for i, s := range obj {
        powers[i] = s.Power
    }
    return powers

} 

My issue is that the obj := make([]*mystruct, 15) creates a slices of 15 *mystruc pointers initialized to nil; which causes the code within the for loop to raise a panic of type "invalid memory or nil pointer dereference".

My question is what is the proper and fastest way to initialize the slice; (the equivalent of var lst = new List(Of mystruct) in .net)

Regards.

1

1 Answers

4
votes

Use a composite literal and take its address in the loop:

for i := range obj {
    obj[i] = &mystruct{Power: i}
}

Try it on the Go Playground.