如果我有以下接口和结构:
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()方法。我怎么能这么做?
发布于 2013-10-27 11:18:23
在Go中,不可能在接口上创建方法。
惯用的方法不是为接口创建方法,而是创建以接口为参数的函数。在您的示例中,它将采用形状,使用反射包返回相同类型的新实例:
func New(s Shape) Shape { ... }另一种可能是将接口嵌入到struct类型中,在struct类型上创建New-方法。
操场示例:http://play.golang.org/p/NMlftCJ6oK
发布于 2013-10-27 06:55:36
不你不能那样做。接口没有设计成任何类似于构造函数的。构造函数不是您所调用的实例。
https://stackoverflow.com/questions/19615338
复制相似问题