jinzhu / copier

Copier for golang, copy value from struct to struct and more
MIT License
5.58k stars 489 forks source link

特定场景无法匹配到TypeConverter #170

Closed smzgl closed 1 year ago

smzgl commented 2 years ago

copier 在特定场景无法匹配到TypeConverter, 如下面四种场景, 实际上仅有一个能匹配到.

type A struct {
    A int
}

type B struct {
    A int
    b int
}

func Test_A(t *testing.T) {

    opt := copier.Option{
        Converters: []copier.TypeConverter{
            {
                SrcType: A{},
                DstType: B{},
                Fn: func(from interface{}) (interface{}, error) {
                    fmt.Print("match TypeConverter ")
                    return nil, nil
                },
            },
        },
    }

    {
        aa := A{A: 10}
        bb := B{A: 10, b: 100}
        t.Logf("err: %v", copier.CopyWithOption(&bb, &aa, opt))
    }

    {
        aa := map[string]*A{
            "a": &A{A: 10},
        }

        bb := map[string]*B{
            "a": &B{A: 10, b: 100},
        }

        t.Logf("err: %v", copier.CopyWithOption(&bb, &aa, opt))
    }
    {
        aa := []*A{
            &A{A: 10},
        }

        bb := []*B{
            &B{A: 10, b: 100},
        }

        t.Logf("err: %v", copier.CopyWithOption(&bb, &aa, opt))

        // b := B{A: 10, b: 100}
        // dst2 := []*B{&b}
        // t.Logf("copy a->*b err: %v, b: %+v", copier.CopyWithOption(&dst2, []*A{&a}, opt), b)
    }

    {
        aa := struct {
            A []*A
        }{
            A: []*A{&A{A: 10}},
        }

        bb := struct {
            A []*B
        }{
            A: []*B{&B{A: 10, b: 100}},
        }

        t.Logf("err: %v", copier.CopyWithOption(&bb, &aa, opt))

        // b := B{A: 10, b: 100}
        // dst2 := []*B{&b}
        // t.Logf("copy a->*b err: %v, b: %+v", copier.CopyWithOption(&dst2, []*A{&a}, opt), b)
    }

}