在golang中扩展包结构

时间:2018-01-15 10:28:55

标签: go struct

是否可以在golang扩展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请求

1 个答案:

答案 0 :(得分:8)

在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
}
相关问题