I saw a piece of code as below:
Just wondering as the value method of draw()
have been implemented, why could it return the pointer of the struct in fact.
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
}
I think should it be like below to implement a pointer method so that the method CreateShape
could return the pointer of struct?
type Rectangle struct {
}
func (*Rectangle) draw() {
fmt.Println("Draw Rectangle")
}
The return type defined on the CreateShape
method is not a struct but an interface. Therefore CreateShape
can return any type as long as it implements the Shape
interface.