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() +} +```