go - 在 golang 中扩展包结构

标签 go struct

在 golang 中是否有可能扩展结构(比如在其他语言中扩展一个类,并将它与旧语言的函数一起使用)

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

A field declared with a type but no explicit field name is called an embedded field. An embedded field must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.

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

关于go - 在 golang 中扩展包结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48261095/

相关文章:

mongodb - golang 客户端无法连接到 mongo 数据库服务器 - sslv3 警报错误证书

Golang - 如何从矩阵中删除一行?

ios - 在结构中传递法线

c - 如何将 Visual Studio 中的结构打包为包含 uint32_t 的 24 位?

Go Coverage 不包括其他包中的函数

Golang - slice 追加(需要时)不起作用

c# - 我可以在不装箱的情况下通过反射为结构设置值吗?

c++ - 单独构造结构体的数据成员是否合法?

Vim:在 C 中,将结构名称突出显示为 cType

go - 如何从 pkcs12 存储加载 x509 key 对?