在 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 规范将结构中的嵌入类型定义为:

使用类型声明但没有显式字段名称的字段称为 嵌入式字段。嵌入字段必须指定为类型名称 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
}

最新更新