登录
首页 >  Golang >  Go问答

如何调用作为接口传递的对象的嵌入结构方法?

来源:stackoverflow

时间:2024-04-22 21:03:27 320浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《如何调用作为接口传递的对象的嵌入结构方法?》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我的场景要求用户嵌入一个基本结构并实现一个接口。

然后,应该将该结构的实例传递给函数。该函数需要调用基本结构的方法。这失败了

// Given base struct and interface

type Interface interface {
    Do()
}

type BaseStruct struct {
    i int
    s string
}

func (*b BaseStruct) Stuff() {}

// The user needs to create a struct that embeds BaseStruct and to implement Interface:
type CustomStruct struct {
    *BaseStruct
}

func (*c CustomStruct) Do() {}

// The user now instantiates the struct and needs to call a function

inst := CustomStruct{}
SomePackageFun(&inst)

// The below function receives the custom struct, and must call the base struct's method, but this fails

func SomePackageFunc(i Interface) {
    // declaring the function with Interface works but I can't call the methods of BaseStruct
    i.Stuff() // not recognized by the compiler
}

解决方案


如果您希望能够调用接口类型的变量上的方法,则应该将该方法添加到接口中。来自嵌入式结构的方法出于满足接口的目的而计数。要调用不属于接口一部分的任何内容,您必须断言到具体类型(或具有该方法的不同接口类型),这违背了这一点。

今天关于《如何调用作为接口传递的对象的嵌入结构方法?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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