Commit e79bab30 authored by Josh Bleecher Snyder's avatar Josh Bleecher Snyder Committed by Russ Cox

encoding/xml: unmarshal into interfaces

Fixes #6836.

LGTM=rsc
R=golang-codereviews, rsc, r, mike
CC=golang-codereviews
https://golang.org/cl/33140043
parent 4b42ad25
......@@ -284,6 +284,15 @@ func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error {
}
}
// Load value from interface, but only if the result will be
// usefully addressable.
if val.Kind() == reflect.Interface && !val.IsNil() {
e := val.Elem()
if e.Kind() == reflect.Ptr && !e.IsNil() {
val = e
}
}
if val.Kind() == reflect.Ptr {
if val.IsNil() {
val.Set(reflect.New(val.Type().Elem()))
......
......@@ -685,3 +685,30 @@ func TestUnmarshaler(t *testing.T) {
t.Errorf("m=%#+v\n", m)
}
}
type Pea struct {
Cotelydon string
}
type Pod struct {
Pea interface{} `xml:"Pea"`
}
// https://code.google.com/p/go/issues/detail?id=6836
func TestUnmarshalIntoInterface(t *testing.T) {
pod := new(Pod)
pod.Pea = new(Pea)
xml := `<Pod><Pea><Cotelydon>Green stuff</Cotelydon></Pea></Pod>`
err := Unmarshal([]byte(xml), pod)
if err != nil {
t.Fatalf("failed to unmarshal %q: %v", xml, err)
}
pea, ok := pod.Pea.(*Pea)
if !ok {
t.Fatalf("unmarshalled into wrong type: have %T want *Pea", pod.Pea)
}
have, want := pea.Cotelydon, "Green stuff"
if have != want {
t.Errorf("failed to unmarshal into interface, have %q want %q", have, want)
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment