我有以下代码:
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()
相同。
关于go - 在 golang 中将一个函数类型转换为另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46893533/