doushouhe7072 2017-10-23 15:53
浏览 189

在Golang中将一个函数类型转换为另一个函数

I have the following code:

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

Now, I want to use this function as part of this struct:

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
}

Basically, set the value of HealthFunction to GetHealth. Now, when I do the following:

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

This gives me an error and it says cannot use vault.Client.GetHealth (type func(vault.Client) error) as type health.DependencyHealthFunction in field value. How can I do this?

Edit: How DependencyHealthFunction is used?

As its part of Dependency struct, it's simply used as following: d.HealthFunction() where d is a variable of type *Dependency.

  • 写回答

2条回答 默认 最新

  • dselp3944 2017-10-23 16:13
    关注

    This is abstract:

        HealthFunction: vault.Client.GetHealth,
    

    If we were to call HealthFunction(), what code do you expect to run? vault.Client.GetHealth is just a promise that such a function exists; it isn't a function itself. Client is just an interface.

    You need to create something that conforms to Client and pass its GetHealth. For example, if you had a existing DefaultClient such as:

    defaultClient := DefaultClient{}
    

    Then you could pass its function:

        HealthFunction: defaultClient.GetHealth,
    

    Now when you later call HealthFunction() it will be the same as calling defaultClient.GetHealth().

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

    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?