Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map results in surprising key case #104

Closed
evadnoob opened this issue Mar 1, 2019 · 1 comment
Closed

Map results in surprising key case #104

evadnoob opened this issue Mar 1, 2019 · 1 comment

Comments

@evadnoob
Copy link

evadnoob commented Mar 1, 2019

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
@darccio
Copy link
Owner

darccio commented Jul 17, 2020

Works in current master (future 0.3.10).

@darccio darccio closed this as completed Jul 17, 2020
darccio added a commit that referenced this issue Jul 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants