[英]Extend package struct in golang
是否有可能在golang extend struct(类似于在其他语言中扩展一个类,并将其与旧函数一起使用)
我有https://github.com/xanzy/go-gitlab/blob/master/services.go#L287类型SetSlackServiceOptions
package gitlab
// SetSlackServiceOptions struct
type SetSlackServiceOptions struct {
WebHook *string `url:"webhook,omitempty" json:"webhook,omitempty" `
Username *string `url:"username,omitempty" json:"username,omitempty" `
Channel *string `url:"channel,omitempty" json:"channel,omitempty"`
}
我想在我自己的包中添加一些字段。 有可能这样做,我可以用我自己的新类型调用函数SetSlackService吗?
package gitlab
func (s *ServicesService) SetSlackService(pid interface{}, opt *SetSlackServiceOptions, options ...OptionFunc) (*Response, error) {
project, err := parseID(pid)
if err != nil {
return nil, err
}
u := fmt.Sprintf("projects/%s/services/slack", url.QueryEscape(project))
req, err := s.client.NewRequest("PUT", u, opt, options)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
https://github.com/xanzy/go-gitlab/blob/266c87ba209d842f6c190920a55db959e5b13971/services.go#L297
编辑:
我想将自己的结构传递给上面的函数。 它是gitlab包的功能,我想扩展http请求
在go中,结构不能像其他面向对象的编程语言那样像类一样扩展。 我们也不能在现有结构中添加任何新字段。 我们可以创建一个嵌入我们需要在不同包中使用的结构的新结构。
package gitlab
// SetSlackServiceOptions struct
type SetSlackServiceOptions struct {
WebHook *string `url:"webhook,omitempty" json:"webhook,omitempty" `
Username *string `url:"username,omitempty" json:"username,omitempty" `
Channel *string `url:"channel,omitempty" json:"channel,omitempty"`
}
在我们的主程序包中,我们必须导入gitlab
包并嵌入我们的结构如下:
package main
import "github.com/user/gitlab"
// extend SetSlackServiceOptions struct in another struct
type ExtendedStruct struct {
gitlab.SetSlackServiceOptions
MoreValues []string
}
Golang规范将struct中的嵌入类型定义为:
使用类型但没有显式字段名称声明的字段称为嵌入字段。 必须将嵌入字段指定为类型名称T或指向非接口类型名称* T的指针,并且T本身可能不是指针类型。 非限定类型名称充当字段名称。
// A struct with four embedded fields of types T1, *T2, P.T3 and *P.T4
struct {
T1 // field name is T1
*T2 // field name is T2
P.T3 // field name is T3
*P.T4 // field name is T4
x, y int // field names are x and y
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.