You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Map() results in a map with keys that are surprising. For example A struct with member CIDR, its resulting key in the map is cDIR. A member with Name results in a key with name, less surprising but still odd. It's like the Map() call is taking the inverse of the first character always. Is this by design? I think this behavior is in conflict with the documentation: "Keys are capitalized to find each corresponding exported field". The godoc is closer to the behavior.
import (
"fmt"
"testing"
)
type Record struct {
Data map[string]interface{}
Mapping map[string]string
}
func StructToRecord(in interface{}) *Record {
rec := Record{}
rec.Data = make(map[string]interface{})
rec.Mapping = make(map[string]string)
typ := reflect.TypeOf(in)
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
dbFieldName := field.Tag.Get("db")
fmt.Printf("%d %v, tags: %v\n", i, field.Name, dbFieldName)
if dbFieldName != "" {
rec.Mapping[field.Name] = dbFieldName
}
}
mergo.Map(&rec.Data, in)
return &rec
}
func TestStructToRecord(t *testing.T) {
type A struct {
Name string `json:"name" db:"name"`
CIDR string `json:"cidr" db:"cidr"`
}
type Record struct {
Data map[string]interface{}
Mapping map[string]string
}
a := A{Name: "David", CIDR: "10.0.0.0/8"}
rec := StructToRecord(a)
fmt.Printf("rec: %+v\n", rec)
if len(rec.Mapping) < 2 {
t.Fatalf("struct to record failed, no mapping, struct missing tags?, rec: %+v, a: %+v ", rec, a)
}
}
Output:
go test -v
=== RUN TestStructToRecord
0 Name, tags: name
1 CIDR, tags: cidr
rec: &{Data:map[name:David cIDR:10.0.0.0/8] Mapping:map[Name:name CIDR:cidr]}
--- PASS: TestStructToRecord (0.00s)
PASS
ok 0.003s
The text was updated successfully, but these errors were encountered:
Map()
results in a map with keys that are surprising. For example A struct with memberCIDR
, its resulting key in the map iscDIR
. A member withName
results in a key withname
, less surprising but still odd. It's like theMap()
call is taking the inverse of the first character always. Is this by design? I think this behavior is in conflict with the documentation: "Keys are capitalized to find each corresponding exported field". The godoc is closer to the behavior.Output:
The text was updated successfully, but these errors were encountered: