Could a method return a pointer with return type of this method is value

huangapple go评论83阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年7月12日 14:34:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/68342838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定