Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: What is the correct way to have an array of struct? #60

Closed
albertoleal opened this issue Dec 7, 2014 · 2 comments
Closed

Comments

@albertoleal
Copy link

Hi! How can I unmarshal an array of struct elements? (I've tried with ,inline, without , inline)

var data = `
current: batman
options:
  batman: something
  robin: another
`
type Target struct {
    Label    string
    Endpoint string
}
type Targets struct {
    Current string
    Options []Target ",inline"
}

func LoadTargets() (*Targets, error) {
    m := Targets{}
    err := yaml.Unmarshal([]byte(data), &m)
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    fmt.Printf("--- m:\n%v\n\n", m)
    return &m, nil
}

thanks!

@advance512
Copy link

Note that your YAML is equivalent to:

current: batman
options: { batman: something, robin: another }

You are trying to unmarshal a YAML mapping into a Go slice. You could try this with:

current: batman
options:
  - batman: something
  - robin: another

But it still won't work. The problem lies in that the yaml lib looks in Target for a field name 'batman' or 'robin' to put the values into, and of course none exists. (inline only affects structs contained by other structs and isn't relevant here afaik.)

The problem is that the slice is of the element type Target. Change it to:

type Target map[string]string

And things will start working. Or, use this kind of YAML:

current: batman
options:
  - label: batman
    endpoint: something
  - label: robin
    endpoint: another

@albertoleal
Copy link
Author

Great, thank you a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants