Pete Jodo
Pete Jodo

Reputation: 463

Go struct type on an already typed struct

I have a struct called Service in package xyz which multiple api wrappers (Api1, Api2) will use as a base. I want someone who is using the package to call the methods for each API like: xyz.Api1.MethodA(..) and xyz.Api2.MethodB(..)

Right now I'm doing something like this

type struct api1 {
    *Service
}

var Api1 *api1

func init() {
    Api1 = &api1{
        &Service{
            ...
        }
    }
}

func (a *api1) MethodA {
    ...
}

I'm not a fan of this because it seems like a lot of boilerplate. I would rather have Api1 be a Service struct but each service will have different methods so I don't think that's possible unless I could do type Service api1 {...}?

Is there another way to get the desired call by a user to be something like xyz.Api1.MethodA(..) without having to create a new struct type for each api and without having so much boilerplate?

Upvotes: 2

Views: 69

Answers (1)

Ainar-G
Ainar-G

Reputation: 36259

Instead of using global variables you can just create two new types and let users decide how to use them:

type API1Service struct {
    *Service
    api1Param1 int
    // etc.
}

func NewAPI1Service(api1Param1 int) *API1Service { /* ... */ }

// methods on API1Service

type API2Service struct {
    *Service
    api2Param1 int
    // etc.
}

func NewAPI2Service(api2Param1 int) *API2Service { /* ... */ }

// methods on API2Service

Then, your users can do

api := xyz.NewAPI1Service(42)
api.MethodA()
// etc.

Upvotes: 2

Related Questions