douba3975 2019-08-16 12:14
浏览 73
已采纳

将具有返回值的Cast方法转换为具有接口{}的方法

I have a plugin that defines following struct:

type foo struct {
    counter int64
}

type Plugin struct {}

func (p *Plugin) Do() *foo {
    // Do something
    return &foo{123}
}

In my main application, I need to cast the plugin to an interface in order to be able to use Do(). At this moment I do not care about the returned value (pointer to a foo struct), but it would be nice to have it.

Question, how do I cast and define a valid interface, if I do not have access to the foo struct? I tried the following options:

type MyFoo struct {
    counter int64
}

type PluginInterface interface {
    Do() *MyFoo
}

type PluginInterface2 interface {
    Do() interface{}
}

func main() {
    plugin := Plugin{} // this would be code that loads bar as an interface {} from the plugin
    do(&plugin)

}

func do(plugin interface{}) {
    _, ok := plugin.(PluginInterface)
    fmt.Println("OK with own Struct?", ok) // false
    _, ok2 := plugin.(PluginInterface2)
    fmt.Println("OK with generic interface?", ok2) // false
}

However, the cast to PluginInterface and PluginInterface2 fails. Obviously, if I change the method definition of Do() in the plugin to return a generic interface{}, then PluginInterface2 cast would succeed.

Example code: https://play.golang.org/p/rB5zZVChSpc

  • 写回答

1条回答 默认 最新

  • doujiyuan0211 2019-08-16 12:19
    关注

    You can't. Change signature of Plugin.Do() to return a value of type defined outside of the plugin (e.g. defined in a 3rd package used by both your app and the plugin), or to return e.g. interface{}.

    See related questions:

    If you can't change the plugin, you may use reflection to call the method. Example calling the Time.Hour() method:

    var x interface{} = time.Date(2019, 1, 1, 14, 0, 0, 0, time.UTC)
    
    v := reflect.ValueOf(x)
    hour := v.MethodByName("Hour")
    results := hour.Call(nil)
    fmt.Println(results[0])
    

    It outputs (try it on the Go Playground):

    14
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?