在已经有类型的结构体上使用Go的struct类型。

huangapple go评论90阅读模式
英文:

Go struct type on an already typed struct

问题

我有一个名为Service的结构体,在xyz包中,多个API包装器(Api1Api2)将使用它作为基础。我希望使用该包的人可以像这样调用每个API的方法:xyz.Api1.MethodA(..)xyz.Api2.MethodB(..)

目前我正在做这样的事情:

type api1 struct {
    *Service
}

var Api1 *api1

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

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

我不喜欢这种方式,因为它看起来有很多样板代码。我宁愿让Api1成为一个Service结构体,但是每个服务都会有不同的方法,所以我认为这是不可能的,除非我可以这样做:type Service api1 {...}

有没有其他方法可以让用户以xyz.Api1.MethodA(..)这样的方式调用所需的方法,而不必为每个API创建一个新的结构体类型,并且不必有那么多样板代码?

英文:

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?

答案1

得分: 2

不使用全局变量,你可以创建两个新的类型,让用户决定如何使用它们:

type API1Service struct {
    *Service
    api1Param1 int
    // 等等
}

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

// API1Service 的方法

type API2Service struct {
    *Service
    api2Param1 int
    // 等等
}

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

// API2Service 的方法

然后,你的用户可以这样做:

api := xyz.NewAPI1Service(42)
api.MethodA()
// 等等
英文:

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.

huangapple
  • 本文由 发表于 2015年5月18日 23:46:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/30307595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定