Reputation: 157
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?
Upvotes: 3
Views: 5104
Reputation: 55952
Go has the concept of "Constructors" that may cover your use case. Combined with exporting it allows you to encapsulate initialization by hiding specifics of calculation from callers:
package main
//Define declare variables
type Define struct {
len int
breath int
area int
}
func (e Define) Area() int {
return e.area
}
func NewDefine(l, b int) Define {
d := Define{
len: l,
breath: b,
area: calculateArea(l, b),
}
return d
}
The pattern to focus on is the exported NewX
. It is extremely common to see constructors named NewX
which will initialize and return a struct. The above delegates to an un-exported calculateArea
function. Of course there are many different possible ways for you to structure your program. calculateArea
still encapsulates the area calculation for trivial unit testing, while hiding it from callers by not exporting it.
Upvotes: 0
Reputation: 279
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)
}
Upvotes: 4