Pierre Prinetti
Pierre Prinetti

Reputation: 9612

Golang: map to struct

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

Answers (2)

rolevax
rolevax

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

ymg
ymg

Reputation: 1500

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"]}

Upvotes: 2

Related Questions