0

I'm trying to initialize structs from a list of strings, but the compiler is throwing the following error. I'm still learning the language so excuse my ignorance, but is this solved by utilizing type assertion?

ERROR: v.UberX undefined (type string has no field method UberX)

type Galaxy struct {
    UberX     int64
    UberY     int64
}

func main() {
    galaxies := []string{"andromeda", "milkyway", "maffei"}
    for _, v := range galaxies {
        v := &Galaxy{}
    }
    for _, v := range galaxies {
        v.UberX += 1000
        v.UberY += 750
    }
}

1 Answer 1

2

Your Galaxy struct doesn't even store the name, in your attempt there isn't any connection between the names and the struct values. Add the name to the struct:

type Galaxy struct {
    Name  string
    UberX int64
    UberY int64
}

Next, in your first loop you create a *Galaxy value, but you only store it in a local variable v which by the way shadows the loop variable v:

for _, v := range galaxies {
    v := &Galaxy{}
}

You need a slice of Galaxy or a slice of *Galaxy which you can populate:

gs := make([]*Galaxy, len(galaxies))

Then 1 loop is enough to loop over the galaxy names and populate the gs slice:

for i, v := range galaxies {
    gs[i] = &Galaxy{
        Name:  v,
        UberX: 1000,
        UberY: 750,
    }
}

Verifying the result:

for _, v := range gs {
    fmt.Printf("%+v\n", v)
}

Output (try it on the Go Playground):

&{Name:andromeda UberX:1000 UberY:750}
&{Name:milkyway UberX:1000 UberY:750}
&{Name:maffei UberX:1000 UberY:750}

Recommended to go through the Golang Tour first to learn the basics.

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

1 Comment

No doubt I've got lots of reading to do. Was hoping I could practice some of it in the meantime. My thought process was that the "name" field would be unnecessary if I could initialize the struct with the proper name. Thanks

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.