迫于需求需要在返回参数里面根据条件判断是否多加一个字段。 目前的手段:
type struct1 struct{ xxxx int } type struct2 struct{ additional_info string } func xxx(){ var data interface{} if(condition){ data = struct1{} }else{ data= struct2{} } data.xxxx=123 }
到最后一行会报 data.xxxx undefined (type interface {} is interface with no methods)错误。
请问 golang 有办法使用类型重载或者增删 JSON 字段么?感谢!最好能兼顾效率。
![]() | 1 qq316107934 OP 自己顶一下,这种编译型语言很无解呀 |
![]() | 2 misaka19000 2018-10-10 19:57:55 +08:00 via Android 用 map 不行吗? |
![]() | 3 qq316107934 OP @misaka19000 #2 struct 是 json unmarshal 出来的,不行,struct 转 map 再处理反射效率太低了,对并发有影响 |
4 cin 2018-10-10 20:07:36 +08:00 ![]() type struct1 struct{ xxxx int `json:"xxxx, omitempty"` } tag 加上 omitempty ? |
![]() | 5 cloverstd 2018-10-10 20:07:45 +08:00 via iPhone SetXxxx |
6 unavph 2018-10-10 20:07:4 +08:00 via iPhone ![]() 直接加在 struct1 里 omitempty 不行么? |
![]() | 7 qq316107934 OP |