Reputation: 9612
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?
Upvotes: 4
Views: 4326
Reputation: 1690
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.
Upvotes: 0