FAQ
type Parent struct {
     ID int
     Child interface{}
}

type ChildT struct {
     ID int
}


json string {"ID":2,"Child":{"ID":3}}

When field Child has value ChildT{}, field Child unmarshals into type
map[string]int
When field Child has value &ChildT{}, field Child unmarshals into type
*ChildT.

https://play.golang.org/p/LkbbOz0ytb


--
苏沛

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

  • James Bardin at May 27, 2016 at 1:51 pm

    On Friday, May 27, 2016 at 6:58:13 AM UTC-4, 苏沛 wrote:
    type Parent struct {
    ID int
    Child interface{}
    }

    type ChildT struct {
    ID int
    }


    json string {"ID":2,"Child":{"ID":3}}

    When field Child has value ChildT{}, field Child unmarshals into type
    map[string]int
    When field Child has value &ChildT{}, field Child unmarshals into type
    *ChildT.
    The value for Child is in an `interface{}`. If that interface contains a
    pointer, then Unmarshal can set the values in the Child struct. If the
    interface contains a ChildT value there's nothing it can set, so it uses
    the default type for JSON objects which is `map[string]interface{}`.

    You should generally only unmarshal into an interface if you're expecting
    the default types.

    https://golang.org/pkg/encoding/json/#Unmarshal

    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/d/optout.

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedMay 27, '16 at 10:58a
activeMay 27, '16 at 1:51p
posts2
users2
websitegolang.org

2 users in discussion

苏沛: 1 post James Bardin: 1 post

People

Translate

site design / logo © 2021 Grokbase