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

Interface as fields in struct and interface calls methods which takes input as same struct

在我的例子中,"RequestHandlerProxy" 是一个结构,它的字段作为接口 "IAdapter",接口有许多方法可以调用,该方法的输入作为结构 "RequestHandlerProxy"。请帮我如何处理这个?如何定义值以构造 "RequestHandlerProxy" 并通过?

下面是我的接口结构和方法:接口"IAdapter"在文件"adapters"

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 playground 中的 运行(如果这不能回答您的问题,也许您可​​以修改该代码以提供问题的简化示例)。

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