4

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?

2
  • 1
    Your only option is p := Point{point["X"], point["Y"]). You can't convert a map to a struct implicitly. Commented May 5, 2014 at 21:45
  • 4
    Try github.com/mitchellh/mapstructure Commented May 5, 2014 at 23:01

2 Answers 2

2

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"]}
Sign up to request clarification or add additional context in comments.

1 Comment

If you need to do this for multiple types, you can almost certainly write a generic function using reflection: golang.org/pkg/reflect
0

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.

1 Comment

Hence I disagree with this approach (slow) I disagree with downvoting this as well as it is a valid answer. +1

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.