Open
Description
show case
when call DecodeToData[B]
the "version": "dfg"
should not decode into B.A.Version
field, it should only set into B.Version
package main
import (
"fmt"
"github.com/go-viper/mapstructure/v2"
)
func DecodeToData[T any](input []any) ([]T, error) {
var result []T
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
WeaklyTypedInput: true,
Squash: true,
Result: &result,
TagName: "json",
})
if err != nil {
return nil, err
}
err = decoder.Decode(input)
if err != nil {
return nil, err
}
return result, nil
}
type A struct {
ObjType string `json:"obj_type"`
ObjID int64 `json:"obj_id"`
Version int `json:"version"`
}
type B struct {
Version string `json:"version"`
A
}
func main() {
var input = []any{
map[string]any{
"obj_type": "a",
"obj_id": 1,
"version": "1",
},
map[string]any{
"obj_type": "b",
"obj_id": 2,
"version": "defg",
},
}
result, err := DecodeToData[A](input)
fmt.Println("result1 ", result, err)
result2, err2 := DecodeToData[B](input)
fmt.Println("result2 ", result2, err2)
}
Metadata
Metadata
Assignees
Labels
No labels