AddAs is like Add but as overrides any name stored under the "unpack" key in template's field tags.
(template any, as string)
| 33 | // AddAs is like Add but as overrides any name stored under the "unpack" key in |
| 34 | // template's field tags. |
| 35 | func (r Reflector) AddAs(template any, as string) Reflector { |
| 36 | if another, ok := template.(Reflector); ok { |
| 37 | maps.Copy(r, another) |
| 38 | return r |
| 39 | } |
| 40 | typ := reflect.TypeOf(template) |
| 41 | unpackKey, unpackVal, skip, err := structToUnpackRule(typ) |
| 42 | if err != nil { |
| 43 | panic(err) |
| 44 | } |
| 45 | if as != "" { |
| 46 | unpackVal = as |
| 47 | } |
| 48 | if unpackKey == "" { |
| 49 | panic(fmt.Sprintf("unpack tag not found for Go type %q", typ.String())) |
| 50 | } |
| 51 | types, ok := r[unpackKey] |
| 52 | if !ok { |
| 53 | types = make(map[string]reflect.Type) |
| 54 | r[unpackKey] = types |
| 55 | } |
| 56 | if _, ok := types[unpackVal]; ok { |
| 57 | panic(fmt.Sprintf("unpack binding for JSON field %q and Go type %q already exists", unpackKey, unpackVal)) |
| 58 | } |
| 59 | if skip { |
| 60 | types[unpackVal] = nil |
| 61 | } else { |
| 62 | types[unpackVal] = typ |
| 63 | } |
| 64 | return r |
| 65 | } |
| 66 | |
| 67 | func (r Reflector) Unmarshal(b []byte, result any) error { |
| 68 | var from any |