最後更新於 2021 年 5 月 23 日
在不同程式語言有不同的OOP實現方式,例如JAVA支持extends也支持interface,但是Go並沒有像C或者JAVA的Class類,它只有結構體,用結構體和指針等特性完成一個類的功能。其實class的底層實現就是結構體,物件的引用就是指針,Go語言只是少了class的語法糖而已。
在Go中我們可以定義一個新的型別,該型別由一系列屬性(欄位)組成,每個屬性都有自己的型別和值,這樣的型別我們就稱之為結構體(struct)。
定義新的型別
在說如何定義結構體之前我們要先說一個概念,在Go中可以使用關鍵字 type
來定義一個新的型別:
type myint int func main(){ var a myint = 10 fmt.Println("a = ",a) //a = 10 fmt.Printf("type of a = %T\n",a) //type of a = main.myint }
有了這個概念之後,我們可以通過 type 定義一個結構體。
定義結構體
使用關鍵字 type
和 struct 來定義結構體,把多種資料型態組合在一起變成複雜的型態:
type Book struct { title string // string 型別的屬性 title auth string // string 型別的屬性 auth }
像上述例子的 title
和 auth
都是該結構體中的屬性,這些屬性可以是任何資料型態,包括常見的string,int..等,甚至結構體本身,也可以是函式或者介面。
使用結構體
定義一個為 Book 型別的變數,可以透過下面這種方式來給屬性賦值:
var book1 Book book1.title = "Golang學習筆記" book1.auth = "pluto" fmt.Printf("%v\n",book1) //{Golang學習筆記 pluto}
也可以使用這種方式給屬性賦值:
book1 := Book{"Golang學習筆記", "pluto"} book1 := Book{title:"Golang學習筆記", auth:"pluto"} //此種方式屬性可以任意調整順序
還可以使用 new()函式分配一個指標,此時 book1 為 *Book
型別
book1 := new(Book) fmt.Printf("%T\n",book1) // *main.Book
結合之前學的指針,結構體的 屬性 一樣是可以通過 指針 去修改:
type Book struct { title string auth string } func changAuthor(book *Book){ book1.auth = "abc" } func main(){ var book1 Book book1.title = "Golang學習筆記" book1.auth = "pluto" fmt.Printf("%v\n",book1) //{Golang學習筆記 pluto} changeAuthor(&book1) fmt.Printf("%v\n",book1) //{Golang學習筆記 abc} }
匿名欄位
只寫型別不寫欄位名的方式就稱為匿名欄位,也稱為嵌入欄位。
當匿名欄位是結構體的時候,這個結構體所擁有的全部欄位都會被引入當前定義的這個結構體,和物件導向中的繼承概念有點相似,例如下面這個例子:
type Human struct { name string sex string } type SuperMan struct { Human //匿名欄位,代表 superMan 引入了Human 的所有欄位 level int } func main(){ s := SuperMan{ Human{"小明","男"}, 100} fmt.Println("name = ", s.name) // 小明 fmt.Println("sex = ", s.sex) // 男 fmt.Println("level = ", s.level) // 100 }
Latest posts by pluto (see all)
- 解決 preact-router 資源請求路徑錯誤的問題 - 2022 年 6 月 24 日
- [楓之谷私服] 潮流轉蛋機 NPC 腳本優化 - 2022 年 6 月 19 日
- [楓之谷私服] 簡單的飛天椅子(坐騎)改法 v120 - 2022 年 6 月 19 日