Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to extend go struct constructors?

Tags:

go

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.

like image 530
mert inan Avatar asked Dec 07 '25 15:12

mert inan


1 Answers

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.

like image 182
Flimzy Avatar answered Dec 09 '25 20:12

Flimzy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!