用自己的结构(解码的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.

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.

Ok, so i found out, it's quite impossible to cast slices. If you refer to my post:

extStruct := &ExtStruct{
    Subject: myStruct.Subject,
    From:    (*extStruct.Email)(myStruct.From),
    Personalizations: []*extStruct.Personalization{
        To: ([]*extStruct.Email)(myStruct.To),
    }}

The Personalizations slice became:

Personalizations: ([]*extStruct.Personalization{{
    To: castStruct(myStruct.To),
}}),

And

func castStruct(input []*myStruct.Email) []*extStruct.Email {
    output := make([]*extStruct.Email, len(input))
    for index, content := range input {
        output[index] = (*extStruct.Email)(content)
    }
    return output
}

I don't know if there's a more clever way to do this, but this is how i succeeded eventually. Just comment this, if you want an elaboration, and I shall try to provide.