在 Go 中实现 constructor/init 方法的最佳方法是什么

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

我有一个程序如下:

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
}

我在:

中调用上面的程序
package main

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

我想将 Area() 函数作为结构初始化的一部分。目前,我必须为 "Define" 创建一个新对象,即 "y",然后调用 Area 方法。相反,有没有一种方法可以让 Area 方法在我创建对象后自动计算?

我会将 Define 重命名为更好的名称,例如 Geometry。通常在 Golang 中,New... 用作 "constructor"

既然您说过要自动计算面积,请将该面积作为结构字段包含在内。以下是我的处理方式 (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)
}

Go 具有 "Constructors" 的概念,可能涵盖您的用例。结合导出,它允许您通过向调用者隐藏计算细节来封装初始化:

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
}

要关注的模式是导出的 NewX。非常常见的是名为 NewX 的构造函数将初始化和 return 一个结构。上面的委托给了一个未导出的 calculateArea 函数。当然,您可以采用多种不同的方式来构建您的程序。 calculateArea 仍然封装用于简单单元测试的面积计算,同时通过不导出它对调用者隐藏它。