From 99c99a0658d04cb54ce8006cd77c03b5a822e1e5 Mon Sep 17 00:00:00 2001 From: "chen.yang" Date: Fri, 30 Jul 2021 14:57:37 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20Golang=20=E9=9D=A2?= =?UTF-8?q?=E5=90=91=E5=AF=B9=E8=B1=A1=E7=BC=96=E7=A8=8B.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: chen.yang --- .../Language/Go/Basic/Golang_面向对象编程.md | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Software/Development/Language/Go/Basic/Golang_面向对象编程.md diff --git a/Software/Development/Language/Go/Basic/Golang_面向对象编程.md b/Software/Development/Language/Go/Basic/Golang_面向对象编程.md new file mode 100644 index 0000000..9b3267f --- /dev/null +++ b/Software/Development/Language/Go/Basic/Golang_面向对象编程.md @@ -0,0 +1,49 @@ +# Golang 面向对象编程 + +## 1.实现构造函数 + +Golang 没有构造函数这样的概念,可以在每个对象创建后调用一个 Init() 函数: + +```go +type TesA struct { + str string +} + +func (t *TesA) Init(str string) { + t.str = str + fmt.Println("TesA Init "+str+".") +} + +func (t *TesA) TesAFun() { + fmt.Println("TesAFun") +} + +func main() { + t := new(TesA) + t.Init("Hello") + t.TesAFun() +} +``` + +花一些小技巧可以将 new() 和 Init() 合并到一行: + +```go +type TesA struct { + str string +} + +func (t *TesA) Init(str string) *TesA { + t.str = str + fmt.Println("TesA Init "+str+".") + return t +} + +func (t *TesA) TesAFun() { + fmt.Println("TesAFun") +} + +func main() { + t := new(TesA).Init("Hello") + t.TesAFun() +} +```