在golang中扩展包结构

在golang中扩展包结构,go,struct,Go,Struct,在golang extend struct中是否可能(类似于在其他语言中扩展类,并将其与旧类的函数一起使用) 我有类型SetLackService选项 package gitlab // SetSlackServiceOptions struct type SetSlackServiceOptions struct { WebHook *string `url:"webhook,omitempty" json:"webhook,omitempty" ` Username *s

在golang extend struct中是否可能(类似于在其他语言中扩展类,并将其与旧类的函数一起使用)

我有类型SetLackService选项

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"`
}
我想在我自己的包中为类型添加一些字段。我可以用我自己的新类型调用函数setLackService吗

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)
}

编辑:


我想把自己的结构转换成上面的函数。它是gitlab包中的函数,我想在go中扩展http请求,结构不能像其他面向对象编程语言中的类那样扩展。我们也不能在现有结构中添加任何新字段。我们可以创建一个新的结构,嵌入我们需要从不同包中使用的结构

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
}
等级库将结构中的嵌入类型定义为:

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