mapstructure icon indicating copy to clipboard operation
mapstructure copied to clipboard

Slice to slice is nil when the name is the same but the type is different

Open ganxiangdong opened this issue 2 years ago • 0 comments

Hi there,

When I try to convert an embedded slice, if the field name is the same in the slice, but the type is different, every element under the slice will be nil. I hope skip the mismatch field, continue to convert other matching fields. What should I do?

My test code is as follows:

package main

import (
	"fmt"
	"github.com/mitchellh/mapstructure"
)

type G struct {
	Id   int
	Name string
}

type X struct {
	Id   int
	Name int
}

type GA struct {
	List []*G
}

type XA struct {
	List []*X
}

func main() {
	g2 := &GA{
		List: []*G{
			{
				Id:   11,
				Name: "g1",
			},
			{
				Id:   22,
				Name: "g2",
			},
		},
	}
	x2 := &XA{}
	err := mapstructure.Decode(g2, &x2)

	fmt.Printf("%+v \n", x2)
	//output: &{List:[<nil> <nil>]}

	fmt.Println(err)
	//output:
	//2 error(s) decoding:
	//* cannot parse 'List[0].Name' as int: strconv.ParseInt: parsing "g1": invalid syntax
	//* cannot parse 'List[1].Name' as int: strconv.ParseInt: parsing "g2": invalid syntax
}

my mapstructure version is v1.5.0. Looking forward to your reply.

ganxiangdong avatar Jul 20 '23 01:07 ganxiangdong