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
}
}
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
", 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.