dqf2015 2018-12-09 03:54
浏览 352
已采纳

Go接口返回类型

I have an interface like this:

type ViewInterface interface{
    Init() View
}

type View struct{
    Width  int
    Height int
}

So I create a new type from View

type MainView View

func (m MainView) Init() MainView{
 return MainView{
   Width:10,
   Height:10,
 }
}

then I pass the MainView to the following method:

func Render(views ...ViewInterface){
  for _, view := range views {
     v := view.Init()
  }
}

func main() {
  Render(MainView{})
}

But I get this error:

cannot use MainView literal (type MainView) as type ViewInterface in argument to Render: MainView does not implement ViewInterface (wrong type for Init method)
have Init() MainView
want Init() View

Why MianView is not same as View? what is the right way to solve this problem?

thanks

  • 写回答

2条回答 默认 最新

  • dongyuhui0418 2018-12-09 04:24
    关注

    GO has different inheritance model comparing to mainstream languages like Java and C#.

    Why MianView is not same as View?

    Because they are defined differently.

    Init function of MainView returns MainView while interface requires to return View.

    Signature of Init method looks strange, it requires instance of structure because it is structure method and returns new instance of the same structure type.

    Try to design interface around logic of your structures instead of their construction/lifetime:

    type ViewInterface interface{
        Render()
    }
    
    type MainView View
    
    func (m MainView) Render() {
      // do something
    }
    
    type AnotherView
    
    func (m AnotherView) Render() {
      // do something else
    }
    
    func Render(views ...ViewInterface){
      for _, view := range views {
         view.Render()
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么