Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to implement a constructor/init methods in Go

I have a program as below:

package main

//Define declare variables
type Define struct {
    len    int
    breath int
}

//Area calculate area
func (e *Define) Area() (a int) {
    a = e.len * e.breath
    return a
}

I call the above program in:

package main

func main() {
    y := Define{10, 10}
    x := y.Area()
    print(x)
}

I would like make the function Area() as part of struct initialization. Currently, I have to create a new object for "Define" ie "y" and then call the method Area. Instead is there a way that Area methods auto calculates once I create the object?

like image 940
pretty08 Avatar asked Jan 29 '26 09:01

pretty08


1 Answers

I'd rename Define to something better like Geometry. Usually in Golang, New... is used as a "constructor"

Since you said you wanted area to be autocalculated, include the area as a struct field. Here's how I'd go about it (https://play.golang.org/p/4y6UVTTT34Z):

package main

//variables
type Geometry struct {
    len    int
    breath int
    area   int
}

// Constructor
func NewGeometry(len int, breadth int) *Geometry {
    g := &Geometry{len, breadth, Area(len, breadth)}
    return g
}

//Area calculate area
func Area(len, breadth int) (a int) {
    return len * breadth
}

func main() {
    g := NewGeometry(10, 2)
    fmt.Println(g.area)
}
like image 104
Metatrix Avatar answered Jan 31 '26 02:01

Metatrix



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!