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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With