2

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.