接口中的构造方法?(在Golang)

laz*_*wei 4 inheritance constructor struct go go-interface

如果我有以下接口和结构:

package shape

type Shape interface {
    Area()
}

type Rectangle struct {
}

func (this *Rectangle) Area() {}

func New() Shape {
    return &Rectangle{}
}
Run Code Online (Sandbox Code Playgroud)

那么如何将该New()方法(作为构造函数)添加到界面中Shape

用例是如果我有另一个结构 Square

type Square struct {
    Rectangle
}
Run Code Online (Sandbox Code Playgroud)

然后Square将有一个方法Area().但它不会New().我的目的是让任何继承的结构ShapeNew()自动拥有一个方法.我怎样才能做到这一点?

ANi*_*sus 6

在Go中,无法在Interfaces上创建方法.

而不是为接口创建方法,惯用的方法是创建以接口为参数的函数.在你的情况下,它将采用一个Shape,使用reflect包返回相同类型的New实例:

func New(s Shape) Shape { ... }
Run Code Online (Sandbox Code Playgroud)

另一种可能性是将接口嵌入到struct类型中,而是在struct类型上创建New-method.

游乐场示例:http: //play.golang.org/p/NMlftCJ6oK