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.
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())
}