ds0409 2016-10-21 04:02
浏览 15
已采纳

创建结构时正确使用接口

I'm trying to write a small program in which I have a few packages, each with a struct that implements an interface. The idea is that based on user input, I can choose what package to use to build a particular struct and then call a function on it that they're all supposed to have. Since I don't know the type ahead of time, I was under the impression that I could use a interface{} and use that as a forward declaration (see the last code snippet). I have something that looks like this:

package foo

type FooInput struct {
    Bar string
    Baz    int
}

type Foo interface {
    Ding()
    Dong()
}

In another package, bob, I have something like:

type Bob struct {
    foo.FooInput
}
func (mybob *Bob) Ding() {}
func (mybob *Bob) Dong() {}
func MakeBob(foo_input foo.FooInput) (*Bob, error) {
    my_bob := Bob{foo_input}
    return &my_bob, nil
}

In my main package, I have something that looks like so:

data = foo.FooInput("awyiss", 1}
var something interface{}
var err error

switch some_string {
case "foo":
    something, err = bob.MakeBob(foo_input)
case "bar":
    // imagine bar is like foo
    something, err = bar.MakeBar(foo_input)
// imagine other cases
}
something.Dong()

When running / building / etc, I get the following error:

something.Dong undefined (type interface {} is interface with no methods)

I'm a bit confused as to what I'm doing wrong... any clarifiers on how I should use interface{} (if at all) would be extremely helpful!

  • 写回答

2条回答 默认 最新

  • doucong7963 2016-10-21 04:07
    关注

    The variable something is declared as the empty interface. There are no methods on the empty interface. To call the Dong method, declare something as a foo.Foo .

    Change

    var something interface{}
    

    to

    var something foo.Foo 
    

    This assumes that bar being like foo means that bar satisfies the foo.Foo interface.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗