登录
首页 >  Golang >  Go问答

在结构中使用字段,方法接收相同结构的输入

来源:stackoverflow

时间:2024-02-24 08:33:25 410浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《在结构中使用字段,方法接收相同结构的输入》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

在我的例子中,“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)
}

以上就是《在结构中使用字段,方法接收相同结构的输入》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>