英文:
Constructor method in Interface? (in Golang)
问题
如果我有以下接口和结构体:
package shape
type Shape interface {
Area()
New() Shape
}
type Rectangle struct {
}
func (this *Rectangle) Area() {}
func (this *Rectangle) New() Shape {
return &Rectangle{}
}
那么我该如何将New()
方法(作为构造函数)添加到接口Shape
中?
使用场景是,如果我有另一个结构体Square
type Square struct {
Rectangle
}
那么Square
将具有一个Area()
方法。但它不会有New()
方法。我的目的是让任何继承Shape
的结构体自动拥有New()
方法。我该如何做到这一点?
英文:
If I have the following interface and struct:
package shape
type Shape interface {
Area()
}
type Rectangle struct {
}
func (this *Rectangle) Area() {}
func New() Shape {
return &Rectangle{}
}
Then how can I add the New()
method (as a constructor) into the interface Shape
?
The use case is that if I have another struct Square
type Square struct {
Rectangle
}
Then the Square
will have a method Area()
. But it won't have New()
. My purpose is let any struct which inherits Shape
has a New()
method automatically. How can I do that?
答案1
得分: 7
在Go语言中,无法在接口上创建方法。
与其为接口创建方法,惯用的方式是创建以接口为参数的函数。在你的情况下,可以创建一个以Shape为参数并返回相同类型新实例的函数,使用reflect包:
func New(s Shape) Shape { ... }
另一种可能性是将接口嵌入到结构体类型中,然后在结构体类型上创建New方法。
Playground示例:http://play.golang.org/p/NMlftCJ6oK
英文:
In Go, it is not possible to create methods on Interfaces.
Instead of creating methods for interfaces, the idiomatic way is to create functions that takes the Interface as argument. In your case it would take a Shape, returning a New instance of the same type, using the reflect package:
func New(s Shape) Shape { ... }
Another possibility is to embed the interface in a struct type, creating the New-method on the struct type instead.
Playground example: http://play.golang.org/p/NMlftCJ6oK
答案2
得分: 0
不,你不能这样做。接口并不设计有类似构造函数的东西。构造函数不是你在实例上调用的。
英文:
No you can't do that. Interface is not designed to have anything like constructor. A constructor is not something you call on instance.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论