dongwu5743 2019-01-31 12:14
浏览 55

用自己的结构(解码的JSON)初始化外部库结构会产生类型错误

I have a struct, which is decoded from a JSON http POST req. My purpose of having this struct is: - Simplifying JSON request from client - Using the structs property data in another (external library) struct.

If i had to only use the external library struct, the client JSON setup will look confusing. How do i use my structs values inside another struct (and especially their arrays)?

I have a working solution for some of the values with simple types.

Consider the following: Ext lib struct:

type ExtStruct struct {
    From             *Email             
    Subject          string             
    Personalizations []*Personalization
 }

My lib struct:

type MyStruct struct {
         From            *Email             
         Subject          string             
         Personalizations []*Personalization
     }

This is my code as is:

myStruct := &MyStruct{}
err := json.NewDecoder(body).Decode(myStruct)
extStruct := &ExtStruct{
    Subject: myStruct.Subject,
    From:    (*extStruct.Email)(myStruct.From),
    Personalizations: []*extStruct.Personalization{
        To: ([]*extStruct.Email)(myStruct.To),
    }}

The Subjectand From value works, but i'm getting errors when trying to referencing array values. I fail to see where i am wrong. AFAIK there's no other option to "simplify" input JSON from a client, only to reference the values in another bigger struct. I can include the other referenced structs if needed, but think of it as:

type A struct {
    RefB []*B
}

type B struct {
    RefC []*C
    Value string
}
type C struct {
    Value string
}

And i need my struct to refer to C.

  • 写回答

2条回答

  • dpwuvfpu52502 2019-01-31 12:42
    关注

    Maybe I misunderstood, but I would think the ExtStruct initialization would look more like

    extStruct := &ExtStruct{
        From:             myStruct.From,
        Personalizations: myStruct.Personalizations,
    }
    

    https://play.golang.org/p/lqFFBa7SKGg

    If they are incompatibly types, Email and Personalization, you should marshall into ExtStruct directly, or do marshalling between types yourself.

    I think you should clarify your answer, maybe provide a working (but faulty) example.

    评论

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊