英文:
Could a method return a pointer with return type of this method is value
问题
我看到了以下的代码:
只是好奇为什么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
方法就可以返回结构体的指针了:
type Rectangle struct {
}
func (*Rectangle) draw() {
fmt.Println("Draw Rectangle")
}
英文:
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")
}
答案1
得分: 3
CreateShape
方法定义的返回类型不是结构体,而是接口。因此,只要实现了 Shape
接口,CreateShape
可以返回任何类型。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论