4

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

package shape

type Shape interface {
    Area()
}

type Rectangle struct {
}

func (this *Rectangle) Area() {}

func New() Shape {
    return &Rectangle{}
}

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

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

type Square struct {
    Rectangle
}

那么Square就会有一个方法Area()。但它不会有New()。我的目的是让任何继承的结构都自动Shape拥有一个New()方法。我怎样才能做到这一点?

4

2 回答 2

6

在 Go 中,不可能在接口上创建方法。

惯用的方法不是为接口创建方法,而是创建将接口作为参数的函数。在您的情况下,它将采用 Shape,使用反射包返回相同类型的 New 实例:

func New(s Shape) Shape { ... }

另一种可能性是将接口嵌入到结构类型中,而不是在结构类型上创建新方法。

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

于 2013-10-27T11:18:23.827 回答
0

不,你不能那样做。接口没有被设计成具有类似构造函数的东西。构造函数不是您在实例上调用的东西。

于 2013-10-27T06:55:36.667 回答