Question

For some reason (fixed-length data file parsing), I've got a map and I want the elements of the map being saved in a struct.

Let's say:

type Point struct {X, Y int}
point := make(map[string]int)

point["X"] = 15
point["Y"] = 13

p := Point{point} // doesn't work

How do I do that? Or have I taken the wrong path?

Was it helpful?

Solution

As far as I know you cant have automatic mapping like this unless you're using the encoding package, but you can use the following way:

p := Point{X: point["X"], Y: point["Y"]}

OTHER TIPS

If the efficiency is not so important, you can marshal the map into JSON bytes and unmarshal it back to a struct.

import "encoding/json"

type Point struct {X, Y int}

point := make(map[string]int)
point["X"] = 15
point["Y"] = 13

bytes, err := json.Marshal(point)
var p Point
err = json.Unmarshal(bytes, &p)

This maks the code easier to be modified when the struct contains a lot of fields.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top