【问题标题】:How to call an embedded struct method of an object passed as interface?如何调用作为接口传递的对象的嵌入式结构方法?
【发布时间】:2020-05-10 16:53:41
【问题描述】:

我的场景需要用户嵌入一个基本结构并实现一个接口。
然后,应该将该结构的一个实例传递给一个函数。该函数需要调用基本结构的方法。这失败了

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

【问题讨论】:

  • func SomePackageFunc(a Interface) 。如果*CustomStruct 实现了Interface,你就不能用它来调用 SomePackageFunc。请注意,您似乎尝试了类似继承的东西:它不起作用。
  • 感谢您的回复。我会在问题中添加更多细节。我的问题是该函数需要调用用户对象中基本结构的一个方法,但是它抛出了异常
  • 我不知道你想做什么,怎么做以及为什么。

标签: go struct interface


【解决方案1】:

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

【讨论】:

  • 那么有更好的成语来处理这个场景吗?我需要用户实现一个预定义结构的接口(那是因为他需要使用结构的一些方法)。然后,他的结构的一个实例应该被发送到一个函数,应该调用预定义的方法
  • @user1102018 是的,再次向界面添加您需要的内容:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 2015-05-16
  • 2013-04-22
  • 1970-01-01
相关资源
最近更新 更多