我看到一段代码如下:
只是想知道已经实现了value 方法,为什么它实际上可以返回 struct 的指针。draw()
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
可以返回结构的指针?
type Rectangle struct {
}
func (*Rectangle) draw() {
fmt.Println("Draw Rectangle")
}