可以扩展go struct构造函数吗?

可以扩展go struct构造函数吗?

问题描述:

given

type Rectangle struct {
    h, w int
}

func (rec *Rectangle) area() int {
    return rec.w * rec.h
}

Can you define a Square struct using Rectangle, so I can make use of area method? It is absolutely fine if it is not possible. I won't judge the language or cry or get upset. I am just learning the golang.

给出 p>

  type矩形结构{
h,w int  
} 
 
func(rec * Rectangle)area()int {
返回rec.w * rec.h 
} 
  code>  pre> 
 
 

使用Rectangle的 Square code>结构,因此我可以使用area方法吗? 如果不可能的话,那绝对好。 我不会评判语言,哭泣或生气。 我只是在学习golang。 p> div>

Go isn't classically object-oriented, so it doesn't have inheritence. It also doesn't have constructors. What it does have is embedding. Thus this is possible:

type Rectangle struct {
    h, w int
}

func (rec *Rectangle) area() int {
    return rec.w * rec.h
}

type Square struct {
    Rectangle
}

The main limitation here is that there's no way for the area() method to access fields that only exist in Square.

I came to know that the expected way to achieve this behaviour is to write ordinary functions. see MakeSquare

type Rectangle struct {
    h, w int
}

func (rec *Rectangle) area() int {
    return rec.w * rec.h
}

type Square struct {
    Rectangle
}

func MakeSquare(x int) (sq Square) {
    sq.h = x
    sq.w = x
    return
}

func Test_square(t *testing.T) {
    sq := MakeSquare(3)
    assert.Equal(t, 9, sq.area())
}