问题描述
我看到一段代码如下:
只是想知道既然draw()
的value方法已经实现了,为什么它实际上会返回结构体的指针。
type Shape interface {
draw()
}
type Rectangle struct {
}
func (Rectangle) draw() {
fmt.Println("Draw Rectangle")
}
type Square struct {
}
func (Squre) draw() {
fmt.Println("Draw Square")
}
type Circle struct {
}
func (Circle) draw() {
fmt.Println("Draw Circle")
}
type ShapeFactory struct {
}
func (*ShapeFactory) CreateShape(shape string) Shape {
if shape == "Rectangle" {
return &Rectangle{}
} else if shape == "Square" {
return &Square{}
} else if shape == "Circle" {
return &Circle{}
}
return nil
}
我想应该像下面这样实现一个指针方法,使方法CreateShape
可以返回struct的指针吗?
type Rectangle struct {
}
func (*Rectangle) draw() {
fmt.Println("Draw Rectangle")
}
解决方法
CreateShape
方法上定义的返回类型不是结构而是接口。因此,Shape
可以返回任何类型,只要它实现了 pdfminer.six
接口。