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.

    评论

报告相同问题?

悬赏问题

  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?