在已经输入的结构上进行结构类型
Go struct type on an already typed struct
我在 package xyz
中有一个名为 Service
的结构,多个 api 包装器(Api1
、Api2
)将用作基础。我希望使用该包的人为每个 API 调用方法,例如:xyz.Api1.MethodA(..)
和 xyz.Api2.MethodB(..)
现在我正在做这样的事情
type struct api1 {
*Service
}
var Api1 *api1
func init() {
Api1 = &api1{
&Service{
...
}
}
}
func (a *api1) MethodA {
...
}
我不喜欢这个,因为它看起来像很多样板。我宁愿让 Api1 成为一个服务结构,但每个服务都有不同的方法,所以我认为这是不可能的,除非我能做到 type Service api1 {...}
?
是否有另一种方法可以使用户所需的调用类似于 xyz.Api1.MethodA(..)
,而不必为每个 api 创建一个新的结构类型并且没有那么多样板文件?
除了使用全局变量,您还可以创建两个新类型并让用户决定如何使用它们:
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
然后,您的用户可以做
api := xyz.NewAPI1Service(42)
api.MethodA()
// etc.
我在 package xyz
中有一个名为 Service
的结构,多个 api 包装器(Api1
、Api2
)将用作基础。我希望使用该包的人为每个 API 调用方法,例如:xyz.Api1.MethodA(..)
和 xyz.Api2.MethodB(..)
现在我正在做这样的事情
type struct api1 {
*Service
}
var Api1 *api1
func init() {
Api1 = &api1{
&Service{
...
}
}
}
func (a *api1) MethodA {
...
}
我不喜欢这个,因为它看起来像很多样板。我宁愿让 Api1 成为一个服务结构,但每个服务都有不同的方法,所以我认为这是不可能的,除非我能做到 type Service api1 {...}
?
是否有另一种方法可以使用户所需的调用类似于 xyz.Api1.MethodA(..)
,而不必为每个 api 创建一个新的结构类型并且没有那么多样板文件?
除了使用全局变量,您还可以创建两个新类型并让用户决定如何使用它们:
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
然后,您的用户可以做
api := xyz.NewAPI1Service(42)
api.MethodA()
// etc.