douyou2368 2018-05-12 20:05
浏览 190
已采纳

在Go中实现构造函数/ init方法的最佳方法是什么

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?

  • 写回答

2条回答 默认 最新

  • dongnuo3749 2018-05-13 05:24
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,