Go接口(interface)返回类型

标签 go go-interface

我有一个这样的界面:

type ViewInterface interface{
    Init() View
}

type View struct{
    Width  int
    Height int
}

所以我从 View 创建了一个新类型

type MainView View

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

然后我将 MainView 传递给以下方法:

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

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

但是我得到这个错误:

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

为什么 MianViewView 不一样?解决这个问题的正确方法是什么?

谢谢

最佳答案

与 Java 和 C# 等主流语言相比,Go 具有不同的继承模型。

Why MianView is not same as View?

因为它们的定义不同。

MainViewInit函数返回MainView,而接口(interface)要求返回View

Init 方法的签名看起来很奇怪,它需要结构实例,因为它是结构方法并返回相同结构类型的新实例。

尝试围绕结构的逻辑而不是结构/生命周期来设计界面:

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()
  }
}

关于Go接口(interface)返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53689232/

相关文章:

go - 在 `NewCookieStore()` 中传递给 `gorilla/sessions` 的 secret key (或身份验证 key )应该是什么?

linux - 向其他进程发送信号

go - "make: go: command not found"- 尽管 go 二进制文件在 $PATH 中

json - 将 interface{} 直接转换为 Golang 中的 int,其中 interface 将数字存储为字符串

go - 如何在 GO 中将 interface{} 转换为 map

unit-testing - 如何使用相互依赖的接口(interface)方法模拟结构

Golang 访问通用结构的数据元素

pointers - 隐藏 nil 值,理解为什么 golang 在这里失败

string - 有一个像Linux cut一样工作的Go函数吗?

go - 是否需要使用类型断言来访问接口(interface)返回的类型的值?