Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How pass different structures to function?

Tags:

go

I have several different structures.

Here show two:

type AdsResponse struct {
    Body struct {
        Docs []struct {
            ID        int  `json:"ID"`
            // others

        } `json:"docs"`
    } `json:"response"`
    Header `json:"responseHeader"`
}

type OtherResponse struct {
    Body struct {
        Docs []struct {
            ID    int     `json:"ID"`
            // others
        } `json:"docs"`
    } `json:"response"`
    Header `json:"responseHeader"`
}

but i don't know how i can do for this method accepts and return both.

func Get(url string, response Response) (Response, bool) {

    res, err := goreq.Request{
        Uri:         url,
    }.Do()

    // several validations

    res.Body.FromJsonTo(&response)

    return response, true
}

And use like this:

var struct1 AdsResponse
var struct2 OtherResponse

Get("someURL", struct1)
Get("someURL", struct2)

There are any form?

like image 681
desarrolla2 Avatar asked Jul 29 '26 16:07

desarrolla2


1 Answers

Your code example is somewhat confusing since both structs appear to be identical. I'll assume that they differ somewhere in "others".

First, I generally recommend creating a wrapper around these kinds of JSON deserializations. Working directly on the JSON structure is fragile. Most of your program should not be aware of the fact that the data comes down in JSON. So for instance, you can wrap this in an Ads struct that contains an AdsResponse, or just copies the pieces it cares about out of it. Doing that will also make some of the below slightly easier to implement and less fragile.

The most common solution is probably to create an interface:

type Response interface {
    ID() int
}

You make both Ads and Others conform to Response. Then you can return Response. If necessary, you can type-switch later to figure out which one you have and unload other data.

switch response := response.(type) {
case Ads:
    ...
case Other:
    ...
}
like image 193
Rob Napier Avatar answered Aug 01 '26 20:08

Rob Napier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!