接口作为结构中的字段,接口调用将输入作为相同结构的方法



在我的例子中,"RequestHandlerProxy"是一个结构,其字段为接口"IAdapter",接口具有可能调用的方法,该方法具有输入作为结构"RequestHandlerProxy"。请帮我如何使用这个?如何定义值以构造"请求处理程序代理"并传递?

以下是我的接口结构和方法: 接口"IAdapter"在文件"适配器"中

type RequestHandlerProxy struct {
TestMode       bool
coreInstanceId string
adapter        adapters.IAdapter
coreProxy      adapterif.CoreProxy
}
func NewRequestHandlerProxy(coreInstanceId string, iadapter adapters.IAdapter, cProxy adapterif.CoreProxy) *RequestHandlerProxy {
var proxy RequestHandlerProxy
proxy.coreInstanceId = coreInstanceId
proxy.adapter = iadapter
proxy.coreProxy = cProxy
return &proxy
}
func (rhp *RequestHandlerProxy) Adapter_descriptor() (*empty.Empty, error) {
return new(empty.Empty), nil    
}
func (rhp *RequestHandlerProxy) Device_types() (*voltha.DeviceTypes, error) {
return nil, nil
}
func (rhp *RequestHandlerProxy) Health() (*voltha.HealthStatus, error) {    
return nil, nil
}

以下是我在适配器文件中的界面:

type IAdapter interface {
Adapter_descriptor() error
Device_types() (*voltha.DeviceTypes, error)
Health() (*voltha.HealthStatus, error)
}

您提供的代码有点难以遵循(不完整且目的尚不清楚(,因此这里有一个简化的示例,希望能回答您的问题。请注意,从问题标题来看,我假设RequestHandlerProxy实现接口IAdapter的事实使您感到困惑;这可能无关紧要(可能还有其他函数接受IAdapter传入RequestHandlerProxy或您自己的IAdapter实现是有意义的,例如下面的adaptImpl(。

我简化了IAdapter以包含单个函数并将所有内容放在一个文件中。要将其扩展到您的示例中,您需要实现所有三个函数(Adapter_descriptor()Device_types()Health()(。代码可以在 go 操场上运行(如果这不能回答您的问题,也许您可以修改该代码以提供问题的简化示例(。

package main
import "errors"
// IAdapter - Reduced to one function to make this simple
type IAdapter interface {
Adapter_descriptor() error
}
/// NewRequestHandlerProxy - Simplified version of the New function
func NewRequestHandlerProxy(iadapter IAdapter) {
return // code removed to make example simple
}
// adaptImpl - Implements the IAdapter interface
type adaptImpl struct {
isError bool // example only
}
// Adapter_descriptor - Implement the function specified in the interface
func (a adaptImpl) Adapter_descriptor() error {
if a.IsError {
return errors.New("An error happened")
}
return nil
}
func main() {
// Create an adaptImpl which implements IAdapter 
x := adaptImpl{isError: true}
NewRequestHandlerProxy(x)
}

最新更新