go - 在 golang 中将一个函数类型转换为另一个函数

标签 go

我有以下代码:

package vault

type Client interface {
    GetHealth() error
}

func (c DefaultClient)  GetHealth () error {
    resp := &VaultHealthResponse{}
    err := c.get(resp, "/v1/sys/health")
    if err != nil {
        return err
    }
    return nil;
}

现在,我想将此函数用作此结构的一部分:

type DependencyHealthFunction func() error

type Dependency struct {
    Name           string `json:"name"`
    Required       bool   `json:"required"`
    Healthy        bool   `json:"healthy"`
    Error          error  `json:"error,omitempty"`
    HealthFunction DependencyHealthFunction
}

基本上,将 HealthFunction 的值设置为 GetHealth。现在,当我执行以下操作时:

func (config *Config) GetDependencies() *health.Dependency {
    vaultDependency := health.Dependency{
        Name: "Vault",
        Required: true,
        Healthy: true,
        HealthFunction: vault.Client.GetHealth,
    }
    temp1 := &vaultDependency
    return temp1;
}

这给了我一个错误,它说 cannot use vault.Client.GetHealth (type func(vault.Client) error) as type health.DependencyHealthFunction in field value。我怎样才能做到这一点?

编辑:如何使用 DependencyHealthFunction?

作为 Dependency 结构的一部分,它的用法如下:d.HealthFunction() 其中 d 是 *Dependency 类型的变量。

最佳答案

这是抽象的:

    HealthFunction: vault.Client.GetHealth,

如果我们要调用 HealthFunction(),您希望运行什么代码? vault.Client.GetHealth 只是对存在这样一个函数的 promise ;它本身不是一个函数。 Client 只是一个接口(interface)。

您需要创建符合 Client 的内容并传递 its GetHealth。例如,如果您有一个现有的 DefaultClient,例如:

defaultClient := DefaultClient{}

然后你可以传递它的函数:

    HealthFunction: defaultClient.GetHealth,

现在,当您稍后调用 HealthFunction() 时,它将与调用 defaultClient.GetHealth() 相同。

https://play.golang.org/p/9Lw7uc0GaE

关于go - 在 golang 中将一个函数类型转换为另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46893533/

相关文章:

go - 从 reflect.Type 中删除指针

curl - Golang HTTP GET 请求返回 404

mongodb - 如何在 go(lang) 中连接到 mlab mongodb 数据库?

go - 断言失败触发函数

go - 获取标志值失败

go - 随着时间的流逝如何进行操纵?

go - 使用来自不同包 golang 的结构

go - 如何在测试服务器中注入(inject)特定的 IP 地址?戈朗

Golang 包括本地文件

go - 何时在 Go 中刷新文件?